Question

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, or fold-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)))))
Was it helpful?

Solution

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

OTHER TIPS

This looks like homework so I'll only give you pointers:

map takes a procedure and applies to to every element of a list. Thus

(define (is-strings lst)
    (map string? lst))

(is-strings '("hello" 5 sym "89")) ; (#t #f #f #t)

(define (add-two lst)
    (map (lambda (x) (+ x 2)) lst))

(add-two '(3 4 5 6)) ; ==> (5 6 7 8)

filter takes procedure that acts as a predicate. If #f the element is omitted, else the element is in the resulting list.

(define (filter-strings lst)
    (filter string? lst))

(filter-strings '(3 5 "hey" test "you")) ; ==> ("hey" "you")

fold-right takes an initial value and a procedure that takes an accumulated value and a element and supposed to generate a new value:

(fold-right + 0 '(3 4 5 6))      ; ==> 18, since its (+ 3 (+ 4 (+ 5 (+ 6 0))))
(fold-right cons '() '(a b c d)) ; ==> (a b c d) since its (cons a (cons b (cons c (cons d '()))))
(fold-right - 0 '(1 2 3))        ; ==> -2 since its (- 1 (- 2 (- 3 0)))
(fold-right (lambda (e1 acc) (if (<= acc e1) acc e1)) +Inf.0 '(7 6 2 3)) ; ==> 2 

fold-right has a left handed brother that is iterative and faster, though for list processing it would reverse the order after processing..

(fold-left (lambda (acc e1) (cons e1 acc)) '() '(1 2 3 4)) ; ==> (4 3 2 1)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top