Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Haskell: type variables

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×