About Q1: You have to somehow skip over the elements in the list which are not positive numbers. One idea is to first filter
them out, as Chris shows. An alternative would be to filter them out with foldl
itself:
(define (product-of-positives lst) ; pass input list as parameter
(foldl (lambda (acc e) ; acc goes first in your foldl
(if (and (number? e) (positive? e)) ; if it's a positive number
(* e acc) ; then multiply it
acc)) ; otherwise keep same acc
1 ; multiplicative identity
lst)) ; input list
Now, for Q2: your implementation isn't right. For starters, you are not even passing a list as parameter - the list
at the end is a built-in procedure, and you should not name a variable like that to avoid this kind of confusions - better use lst
, for instance.
Let's say you fix that and pass along a list parameter - then you'll find out that the acc
parameter isn't right, if you want to multiply a list then it must be 1
, because we're building a number as the output (not a list), and it can't be 0
because it will cancel out all the values - we're multiplying them after all.
One last thing - using just real?
won't work for picking the positive numbers in the list. Better stick with either of the implementations we've shown:
(product-of-positives '(1 2 3 6 0 -5 "scheme"))
=> 36