mike
mike

Reputation: 49

Scheme Map Function

I am trying to find the length of a list using Map/Foldl/Foldr

(define (suml lst)
(length lst))
Input : (suml '(1 2 3))
Output : 3
Input : (suml '(((((2)))) (1)))
Output: 2

How can I modify it work with foldl/map/foldr?

Upvotes: 0

Views: 1208

Answers (1)

superlizardmo
superlizardmo

Reputation: 333

As has been mentioned in the comments, map takes a function and applies it elementwise. A function that uses map will create a list of the same length. To create a length function, we are condensing a list to a single value. This is the purpose of fold.

(define (length l) (foldr (lambda (_ cur-length) (+ 1 cur-length)) 0 l))

When you think about foldr, you should think about it just replacing cons in a list with the function and the empty list with the base case argument. Take the following example:

'(1 2 3 4) = (cons 1 (cons 2 (cons 3 (cons 4 '())))) (foldr f base '(1 2 3 4)) = (f 1 (f 2 (f 3 (f 4 base))))

It turns out, foldl also works in this case because we're just adding one for every element, it doesn't matter if we go left to right or right to left.

(define (length l) (foldl (lambda (_ cur-length) (+ 1 cur-length)) 0 l))

Upvotes: 2

Related Questions