What is a parametrically polymorphic function?

Can someone explain this to me regarding sorting algorithms?

+5
source share
3 answers

Let me try the simplest thing I can.

Suppose you have a pair of integers:

foo :: (Int, Int) 
foo = (2,5)

and suppose you need a function that changes the position of integers on this pair. You can do it:

swapInt :: (Int, Int) -> (Int, Int)
swapInt (x,y) = (y,x)

But now, if you need a similar function for Doubles, you will have to implement it again:

swapDouble :: (Double, Double) -> (Double, Double)
swapDouble (x,y) = (y,x)

: (1) swapDouble swapInt , , (2) , , x y. . , , , . . :

swap :: (a,b) -> (b,a)
swap (x,y) = (y,x)

? : swap, (x, y), x a, y b (y, x). a b , . swap , , .

:

swap ('a', 1) = (1,'a')  -- in this case swap :: (Char, Int) -> (Int, Char) 
swap ( 0 , 5) = (5, 0 )  -- in this case swap :: (Int , Int) -> (Int, Int )

: polymorphic - , . , " " . (a,b), a b .

, : , , , ,... . , : , , ,... , , .

, Haskell , , ad hoc- .

+7

, , .

linear_search f n [] = Nothing
linear_search f n (x:xs)
    | f n x     = Just x
    | otherwise = linear_search f n xs

, , - , .

, linear_search ; , ( ) ( ).

# preforming on integers
linear_search (==) 5 [1,2,3,4,5]
# returns Just 5

# preforming on strings
linear_search (elem) 'e' ["doctor", "apron", "horse", "sky"]
# returns Just "horse"

, (a -> b -> Bool) -> a -> [b] -> Maybe b. , , , - , .

+6

, , . - , .

- from: http://en.wikipedia.org/wiki/Polymorphism_(computer_science).

Regarding searches, I think it depends more on the specific context - I can not help there.

+2
source

All Articles