Anonymous recursion: Difference between revisions
Content added Content deleted
No edit summary |
(translated haskell to ocaml) |
||
Line 744: | Line 744: | ||
return 0; |
return 0; |
||
}</lang> |
}</lang> |
||
=={{header|OCaml}}== |
|||
{{trans|Haskell}} |
|||
OCaml has two ways to use anonymous recursion. Both methods hide the 'anonymous' function from the containing module, however the first method is actually using a named function. |
|||
'''Named function:''' |
|||
We're defining a function 'real' which is only available from within the fib function. |
|||
<lang ocaml>let fib n = |
|||
let rec real = function |
|||
0 -> 1 |
|||
| 1 -> 1 |
|||
| n -> real (n-1) + real (n-2) |
|||
in |
|||
if n < 0 then |
|||
None |
|||
else |
|||
Some (real n)</lang> |
|||
'''Anonymous function:''' |
|||
This uses the 'fix' function to find the fixed point of the anonymous function. |
|||
<lang ocaml>let rec fix f x = f (fix f) x |
|||
let fib n = |
|||
if n < 0 then |
|||
None |
|||
else |
|||
Some (fix (fun f -> fun n -> if n <= 1 then 1 else f (n-1) + f (n-2)) n)</lang> |
|||
{{out}} |
|||
<pre># fib 8;; |
|||
- : int option = Some 34</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |