I've been hearing all sorts of stuff about Haskell lately. It's a programming language that has all of my favorite features: it's a functional language, it uses pattern matching on function definitions, and it's got a very sparse, simple, syntax
(
Read more... )
Comments 2
Reply
A slightly more interesting use of lazy evaluation is the Haskell approach to the Fibonacci sequence.
nac = 1 : 1 : [ a+b | (a,b) <- zip nac (tail nac)]
That returns a list containing every value in the Fibonacci sequence.
The zip nac (tail nac) takes nac (the list of all Fib numbers) and the tail of nac (all but the first element in that list) and interleaves them, (a,b) <- takes the result of zip and turns it into a pair of values- literally, it takes the first two elements out of the zip result and names them "a" and "b". So this whole phrase, [ a+b | (a,b) <- zip nac (tail nac)] says, zip up the Fibonacci sequence and all but the first element of the Fibonacci sequence, pop off each element into pairs, and add each half of the pair to produce a list.
Crazy recursive code that works because of lazy evaluation.
Reply
Leave a comment