Wednesday, November 18, 2009

Recursive Function - example 2

ב''ה


A Haskell recursive function I read about to duplicate the drop function:
myDrop n xs = if n <= 0 || null xs
then xs
else myDrop (n - 1) (tail xs)

ghci> :load myDrop.hs
[1 of 1] Compiling Main ( myDrop.hs, interpreted )
Ok, modules loaded: Main.
ghci> myDrop 2 "foobar"
"obar"

Again, I wrote it out for better understanding. 



The function calls would look like this:
2 foobar
1 oobar
0 obar - which gets assigned.


Or like this:
ghci> myDrop 4 "foobar"
"ar"

4 foobar
3 oobar
2 obar
1 bar
0 ar - which gets assigned.



Only the last function call returns a value because of Haskell's lazy evaluation feature. The value only needs to be evaluated when the "then xs" expression is reached.

No comments:

Post a Comment