Sep 17, 2010

Haskell folds

Folds - a flod apply a function to a list, accumilate items and give a single output.
There are 4 main fold functions;
foldr - this will fold up a list from the last element to the first element and apply a given function for each element.

fac n = foldr (*) 2 [1..n]

if you run this code and type as;
fac 3
it will give the output as
12
What will happen in this is,
3*2 + 2*2 + 1*2 = 12

foldl - this will go from the first element to the last element.
foldl1 and foldr1 -
these things will work as the way the foldl and foldr work. But this will give an error message when it is an empty array.

scan
This do the both things done by map and fold. It will accumilate values like fold but the output will be given as a list as in map for each intermediate value.

scanl (+) 0 [1,2,3]
this will give the output as
[0,1,3,6]

Data types

data SpecialDay = Birthday Int Int Int
| Wedding String Int Int Int
SpecialDay is a data which can be ether a birthday or a wedding. So,

mySpeDay :: SpecialDay
mySpeDay = Birthday 1988 09 16

No comments:

Post a Comment

Your comments are always welcome ...