使用scheme递归地将值y添加到lambda x

问题描述 投票:1回答:1

我一直在尝试各种组合,但似乎找不到合适的组合。我要做的是将变量y添加到列表x中的每个元素,并打印出带有结果的列表(y + x_1 + y + x_2 ... y + x_n)。

这是我的方案代码:

(define (incall y) 
  (lambda (x)
    (if (null? (cdr x))
       x ;;Tried several variations
    (+ y x) ;;Same here (using car/cdr /cons)
    )
  )
)

我正在实施的数字是:

    ((incall 2) '(1 2 3)) 

并且应该屈服。

    (2 3 4)

感谢任何帮助,并解释我做错了什么。

recursion lambda scheme racket
1个回答
1
投票

您需要命名您的curried程序,以便您可以将其用于列表的其余部分:

(define (add-list intial-value) 
  (define (curried-proc lst)
     ...)
  curried-proc) ; return the proc

我不知道为什么你会想要这个界面。我本来喜欢做(add-list 2 '(1 2 3)) ; ==> (3 4 5),然后你会这样做:

(define (add-list initial-value lst) 
  (define (helper lst)
     ...)
  (helper lst)) ; return the result of calling helper

所以对帮助者来说..你需要只处理第一个元素,如果不是null则递归其余元素。对于null,它应该为null。例如。

(define (helper lst)
  (if (null? lst) 
      <??>                        ; what is the result of (incall 5 '())
      (cons <calculate>           ; what whould (car x) be replaced with?
            (helper (cdr lst)))))

现在帮助器可以用命名的let替换。一样的。这是与您正在制作的类似的工作版本:

(define (halve-list lst)
  (let helper ((lst lst))
    (if (null? lst)
        '()
        (cons (/ (car lst) 2)
              (helper (cdr lst))))))

(halve-list '(1 2 3 4)) ; ==> (1/2 1 3/2 2)

另一种方法是使用map,因为它会处理大部分帮助程序,除了对每个元素执行的操作:

(define (halve-list lst)
  (map (lambda (e) (/ e 2)) lst))
© www.soinside.com 2019 - 2024. All rights reserved.