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?
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))
mapbecausemapapplies 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, sincelengthis already a function that gets the length of a list. Just drop themapand use(length lst)(and at that point, you can drop thesumlwrapper, since it’s justlength). Or are you actually trying to do something else?