ב''ה
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.
Showing posts with label Recursion. Show all posts
Showing posts with label Recursion. Show all posts
Wednesday, November 18, 2009
Tuesday, November 17, 2009
(attempt grasp this weird stuff)
ב''ה
Thank you for visiting my blog. This blog is to attempt to grasp and explain functional programing and other cool programing things.
My latest attempt at understanding this stuff was going through this article:
http://www.defmacro.org/ ramblings/fp.html
The pseudo-code recursive function was too hard to understand so I wrote out what each function call would come back as.
String reverse(String arg) {
if(arg.length == 0) {
return arg;
}
else {
return reverse(arg.substring(1, arg.length)) + arg.substring(0, 1);
}
}
If you would pass in the string "string" this is what would happen:
What would be passed in on each recursive call:
string -length 6
tring + s - length 5
ring + t - length 4
ing + r - length 3
ng + i - length 2
g + n - length 1
'' + g - length 0
In order, what would be returned:
return g
return gn
return gni
return gnir
return gnirt
return gnirts
Thank you for visiting my blog. This blog is to attempt to grasp and explain functional programing and other cool programing things.
My latest attempt at understanding this stuff was going through this article:
http://www.defmacro.org/
The pseudo-code recursive function was too hard to understand so I wrote out what each function call would come back as.
String reverse(String arg) {
if(arg.length == 0) {
return arg;
}
else {
return reverse(arg.substring(1, arg.length)) + arg.substring(0, 1);
}
}
If you would pass in the string "string" this is what would happen:
What would be passed in on each recursive call:
string -length 6
tring + s - length 5
ring + t - length 4
ing + r - length 3
ng + i - length 2
g + n - length 1
'' + g - length 0
In order, what would be returned:
return g
return gn
return gni
return gnir
return gnirt
return gnirts
Subscribe to:
Posts (Atom)