Factorial: Difference between revisions
Content added Content deleted
(→Soda: Tail recursive) |
m (scheme syntax highlight) |
||
Line 9,370: | Line 9,370: | ||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
===Recursive=== |
===Recursive=== |
||
<syntaxhighlight lang="scheme"> |
<syntaxhighlight lang="scheme"> |
||
(define (factorial n) |
|||
(if (<= n 0) |
(if (<= n 0) |
||
1 |
1 |
||
(* n (factorial (- n 1))))) |
(* n (factorial (- n 1))))) |
||
</syntaxhighlight> |
|||
The following is tail-recursive, so it is effectively iterative: |
The following is tail-recursive, so it is effectively iterative: |
||
<syntaxhighlight lang="scheme"> |
<syntaxhighlight lang="scheme"> |
||
(define (factorial n) |
|||
(let loop ((i 1) |
(let loop ((i 1) |
||
(accum 1)) |
(accum 1)) |
||
(if (> i n) |
(if (> i n) |
||
accum |
accum |
||
(loop (+ i 1) (* accum i))))) |
(loop (+ i 1) (* accum i))))) |
||
</syntaxhighlight> |
|||
===Iterative=== |
===Iterative=== |
||
<syntaxhighlight lang="scheme"> |
<syntaxhighlight lang="scheme"> |
||
(define (factorial n) |
|||
(do ((i 1 (+ i 1)) |
(do ((i 1 (+ i 1)) |
||
(accum 1 (* accum i))) |
(accum 1 (* accum i))) |
||
((> i n) accum))) |
((> i n) accum))) |
||
</syntaxhighlight> |
|||
===Folding=== |
===Folding=== |
||
<syntaxhighlight lang="scheme"> |
<syntaxhighlight lang="scheme"> |
||
;Using a generator and a function that apply generated values to a function taking two arguments |
|||
;A generator knows commands 'next? and 'next |
;A generator knows commands 'next? and 'next |
||
Line 9,409: | Line 9,418: | ||
(factorial 8) |
(factorial 8) |
||
;40320 |
;40320 |
||
</syntaxhighlight> |
|||
=={{header|Scilab}}== |
=={{header|Scilab}}== |