Idiomatic use of local vs lambda?

In Exercise 30.1.1 of HtDP , I started using localand then modified it to use lambdato answer a question.

(define (add-to-each2 accu a-list)
  (cond
    [(empty? a-list) empty]
    [else (local ((define s (+ accu (first a-list))))
            (cons s (add-to-each2 s (rest a-list))))]))

and

(define (add-to-each5 accu a-list)
  (cond
    [(empty? a-list) empty]
    [else (cons ((lambda (x y)
                   (first (map + (list (first y))
                               (list x)))) accu a-list)
                (add-to-each5 (+ accu (first a-list))(rest a-list)))]))

In this particular case, the version is localeasier for me to read. Are there situations where a version is preferred lambda? Thank.

+3
source share
1 answer

Firstly, I think that you can lose relative-2-absolutewith add-to-each, as it add-to-eachsimply adds the same number to each element of the list, rather than increasing it. The rest of this post assumes a case, and simply extracts this increment.

, let . lambda , let lambda :

(let ([x e]) body)

:

((lambda (x) body) e)

lambda let , :

(define (add-to-each5 n a-list)
  (cond
    [(empty? a-list) empty]
    [else (cons (let ([x n] [y a-list])
                  (first (map + (list (first y))
                              (list x))))
                (add-to-each5 n (rest a-list)))]))

, , , , . , " lambda" , let.

, 30.1.1 map , . map , , map : (list (first y)) (list x), (+ (first y) x)?

map, , , , :

(define (map f ls)
  (cond
    [(empty? ls) empty]
    [else (cons (f (first ls)) (map f (rest ls)))]))

, add-to-each: cond , cons - first map rest. map a f, , .

add-to-each . 2:

> (map (lambda (n) (+ 2 n)) (list 1 2 3 4 5))
(3 4 5 6 7)

, map lambda 30.1.1, add-to-each: map.

, ; , :)

+3

Source: https://habr.com/ru/post/1786308/


All Articles