0

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?

3
  • You cannot find the length of a list using map because map applies a function to each element of a list, but knowing the length requires having information about the whole list. Your code is a bit silly though, since length is already a function that gets the length of a list. Just drop the map and use (length lst) (and at that point, you can drop the suml wrapper, since it’s just length). Or are you actually trying to do something else? Commented Oct 20, 2016 at 4:52
  • How should the function work. Can you give example input and expected result? Commented Oct 20, 2016 at 7:59
  • I updated the OP , please check :) Sylwester Alexis King Commented Oct 20, 2016 at 13:36

1 Answer 1

2

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))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.