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">(define (factorial n)
<syntaxhighlight lang="scheme">
(define (factorial n)
(if (<= n 0)
(if (<= n 0)
1
1
(* n (factorial (- n 1)))))</syntaxhighlight>
(* 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">(define (factorial n)
<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)))))</syntaxhighlight>
(loop (+ i 1) (* accum i)))))
</syntaxhighlight>

===Iterative===
===Iterative===
<syntaxhighlight lang="scheme">(define (factorial n)
<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)))</syntaxhighlight>
((> i n) accum)))
</syntaxhighlight>

===Folding===
===Folding===
<syntaxhighlight lang="scheme">;Using a generator and a function that apply generated values to a function taking two arguments
<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</syntaxhighlight>
;40320
</syntaxhighlight>


=={{header|Scilab}}==
=={{header|Scilab}}==