Wednesday, June 4, 2008

haskell power!

i'm still reading a book on haskell - "Haskell - The Craft of Functional Programming".

nice introductory and overall stuff.

so, haskell have a lot of high level functions(what a surprise for a functional programming language!), today two of them impressed me.

1) iterate: "creates an infinite list where the first item is calculated by applying the function on the secod argument, the second item by applying the function on the previous result and so on".

Input: take 10 (iterate (2*) 1)

[1,2,4,8,16,32,64,128,256,512] ('take' takes first n items of a list)

so it takes an argument as a starting point and continues applying function to it.

it can take lambda functions, like this:

Input: take 10 (iterate (\x -> (x+3)*2) 1)

[1,8,22,50,106,218,442,890,1786,3578]

and i thought that this can be used to calculate fibonacci numbers!

take 10 (iterate (\(x,y)->(y,x+y)) (1,1))

[(1,1),(1,2),(2,3),(3,5),(5,8),(8,13),(13,21),(21,34),(34,55),(55,89)]

2) list comprehensions. not exactly a function, but very nice construct. they may return infinite lists.

it should be pretty much familiar to python programmers, though more powerful.

[ f x | p1, p2, p3... ]

each value can be transformed by function f
p1, p2... - conditions that evaluate to boolean OR generators

"so what" you may say, nothing new. yeah, except p1, p2... can use values from generators on the left!

e.g., we can have a infinite list of pythagorean triples:

[ (x,y,z) | z <- [2..], y <- [2..z-1], x <- [2..y-1], x^2 + y^2 == z^2 ]

[(3,4,5),(6,8,10),(5,12,13),(9,12,15),(8,15,17),(12,16,20),(15,20,25),(7,24,25),(10,24,26),(20,21,29)]

i was really excited about those two. enough to blog about 'em :)

No comments: