Factorial: Difference between revisions

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

edits