Saturday, 30 April 2016

Haskell: type variables

When you want to write a polymorphic function, you can use type variable. Type variables is represented by any lower case letter like a, b, c.... and it is replaced by real data types like Integer, Double, Bool etc.,

Suppose, you want to calculate total number of elements in a list, you can write a function signature like below.

lengthOfList :: [a] -> Int
lengthOfList is a function, which takes list of elements of any type a and return total number of elements, which is an Int.

lastButOne :: [a] -> a
lastButOne  is a function which takes a list of any type elements and return last but one (The element before the last element) element. In both the example, ‘a’ represent type variable.


listUtil.hs
{- Get total number of elements in a list -}
lengthOfList :: [a] -> Int
lengthOfList [] = 0
lengthOfList(x:xs) = 1 + lengthOfList(xs)

{- Return last but one of the list -}
lastButOne :: [a] -> a
lastButOne (x:xs) = if length xs == 1
                    then x
                    else lastButOne xs



Previous                                                 Next                                                 Home

No comments:

Post a Comment