You are given a list of strings.
Generate a procedure such that applying this procedure to such a list would result in a list of the lengths of each of the strings in the input.
Use
map
,filter
, orfold-right
.(lengths (list "This" "is" "not" "fun")) => (4 2 3 3) (define lengths (lambda (lst) your_code_here))
I got stuck in the following code and I do not understand how can I use filter
.
(define lengths
(lambda (lst)
(if (null? lst)
nil
(fold-right list (string-length (car lst)) (cdr lst)))))
This seems like a work for map
, you just have to pass the right procedure as a parameter:
(define (lengths lst)
(map string-length lst))
As you should know, map
applies a procedure to each of the elements in the input list, returning a new list collecting the results. If we're interested in building a list with the lengths of strings, then we call string-length
on each element. The procedure pretty much writes itself!
A word of advice: read the documentation of the procedures you're being asked to use, the code you're writing is overly complicated. This was clearly not a job for filter
, although fold-right
could have been used, too. Just remember: let the higher-order procedure take care of the iteration, you don't have to do it explicitly:
(define (lengths lst)
(fold-right (lambda (x a)
(cons (string-length x) a))
'()
lst))