Mutual recursion: Difference between revisions
Content added Content deleted
(added standard ml) |
|||
Line 545: | Line 545: | ||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
<code>define</code> declarations are automatically mutually recursive: |
|||
Could probably be optimized with tail recursion. |
|||
<lang scheme> |
<lang scheme> |
||
(define (F n) |
(define (F n) |
||
Line 555: | Line 555: | ||
(- n (F (M (- n 1)))))) |
(- n (F (M (- n 1)))))) |
||
</lang> |
</lang> |
||
If you wanted to use a <code>let</code>-like construct to create local bindings, you would do the following. The <code>define</code> construct above is just a syntactic sugar for the following where the entire rest of the scope is used as the body. |
|||
<lang scheme> |
|||
(letrec ((F (lambda (n) |
|||
(if (= n 0) 1 |
|||
(- n (M (F (- n 1))))))) |
|||
(M (lambda (n) |
|||
(if (= n 0) 0 |
|||
(- n (F (M (- n 1)))))))) |
|||
(F 19)) # evaluates to 12 |
|||
</lang> |
|||
The <code>letrec</code> indicates that the definitions can be recursive, and fact that we placed these two in the same <code>letrec</code> block makes them mutually recursive. |
|||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |