Factorial diagram (fact * 1) Question
I'm new to Scheme, so forgive the question: I have a function that calculates the factorials of a list of numbers, but that gives me the period until the last number in the results. Where am I going wrong?
code:
#lang scheme
(define fact
(lambda (n)
(cond
((= n 0) 1)
((= n 1) 1)
(else (* n (fact (- n 1)))))))
(define fact*
(lambda (l)
(cond
((null? (cdr l)) (fact (car l)))
(else
(cons (fact (car l)) (fact* (cdr l)))))))
Output:
> (fact* '(3 6 7 2 4 5))
(6 720 5040 2 24 . 120)
source to share
What did you do, create the wrong list . Try the following:
(define fact*
(lambda (l)
(cond
((null? (cdr l)) (list (fact (car l))))
(else
(cons (fact (car l)) (fact* (cdr l)))))))
The addition list
on the fourth line should make this work as you expect. The following might be better:
(define fact*
(lambda (l)
(cond
(null? l) '())
(else
(cons (fact (car l)) (fact* (cdr l)))))))
This allows your function fact*
to run on an empty list, as well as reduce the number of places you make a call fact
.
source to share
the other answers have provided a reason why you are getting the wrong list as a result of yours fact*
. I would only like to point out that you can use a higher order function map
:
(define fact*
(lambda (l)
(map fact l))
(fact* '(3 6 7 2 4 5))
map
takes a function and a list as arguments and applies the function to each item in the list, creating a new list.
source to share
Use append
instead cons
. cons
used to build pairs, so you have "." which is used to separate the elements of a pair. Here's an example:
(define (factorial n)
(if (<= n 1)
1
(* n (factorial (- n 1)))))
(define (factorial-list l)
(if (null? l)
'()
(append (list (factorial (car l)))
(factorial-list (cdr l)))))
source to share