Anonymous recursion: Difference between revisions

Added Standard ML section
m (fix header)
(Added Standard ML section)
Line 1,792:
}(i).to_s.say;
} * 10;</lang>
 
=={{header|Standard ML}}==
ML does not have a built-in construct for anonymous recursion, but you can easily write your own fix-point combinator:
<lang sml>fun fix f x = f (fix f) x
 
fun fib n =
if n < 0 then raise Fail "Negative"
else
fix (fn fib =>
(fn 0 => 0
| 1 => 1
| n => fib (n-1) + fib (n-2))) n</lang>
 
Instead of using a fix-point, the more common approach is to locally define a recursive function and call it once:
<lang sml>fun fib n =
let
fun fib 0 = 0
| fib 1 = 1
| fib n = fib (n-1) + fib (n-2)
in
if n < 0 then
raise Fail "Negative"
else
fib
end</lang>
 
In this example the local function has the same name as the outer function. This is fine: the local definition shadows
the outer definition, so the line "fib n" will refer to our helper function.
 
Another variation is possible. Instead, we could define the recursive "fib" at top-level, then shadow it with a non-recursive wrapper. To force the wrapper to be non-recursive, we use the "val" syntax instead of "fun":
<lang sml>fun fib 0 = 0
| fib 1 = 1
| fib n = fib (n-1) + fib (n-2)
 
val fib = fn n => if n < 0 then raise Fail "Negative"
else fib n</lang>
 
=={{header|Tcl}}==
Anonymous user