0

你会得到一个字符串列表。

生成一个过程,以便将此过程应用于此类列表将导致输入中每个字符串的长度列表。

使用mapfilterfold-right

(lengths (list "This" "is" "not" "fun")) => (4 2 3 3)

(define lengths (lambda (lst) your_code_here))

我陷入了以下代码中,我不明白如何使用filter.

(define lengths
  (lambda (lst)
    (if (null? lst)
        nil
        (fold-right list (string-length (car lst)) (cdr lst)))))
4

2 回答 2

1

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))
于 2013-11-12T01:00:12.653 回答
0

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)
于 2013-11-12T01:03:09.077 回答