Scheme:Lambda Recursion:按元素组合两个列表元素

时间:2014-01-22 22:32:00

标签: scheme

我刚开始学习Scheme,我们得到了匿名函数。我们正在学习如何递归lambda,我理解递归单变量函数,比如查找factorial,但我将如何为下面的函数执行此操作?

    (define (two-list list1 list2)
      (cond
        [(empty? list1) empty]
        [else (cons (string-append (first list1)(first list2))
                     (two-list (rest list1)(rest list2)))]))

在这里,我试图获取两个字符串列表,并按元素组合它们。

1 个答案:

答案 0 :(得分:1)

编写一个接收两个列表作为参数的递归函数与实现单参数函数没有什么不同:根据您要解决的问题规则,依次处理每个元素并在两个列表上前进。实际上,您发布的代码没有任何问题(假设两个列表具有相同的长度)。这是执行它的结果:

(two-list '("1" "2" "3") '("4" "5" "6"))
=> '("14" "25" "36")

或许有些评论会说清楚:

(define two-list        ; code 100% equivalent to the one in the question
  (lambda (list1 list2) ; here lambda is explicit, it was implicit before
    (cond
      [(empty? list1) ; if one list is finished then
       empty]         ; end recursion and return the empty list
      [else           ; otherwise
       (cons (string-append  ; cons the result of performing an operation
              (first list1)  ; over the first list's first element and
              (first list2)) ; the second list's first element
             (two-list       ; finally, advance the recursion
              (rest list1)   ; over the first list and
              (rest list2)))]))) ; over the second list too

<强>更新

作为评论中提到的概念的证明,这里是如何使用Y-Combinator实现相同的过程。这样,我们不需要define任何东西:

(((λ (X) ; Y-Combinator
    ((λ (proc)
       (proc proc))
     (λ (proc)
       (X (λ (arg1 arg2)
            ((proc proc) arg1 arg2))))))
  (λ (two-list) ; `two-list` procedure it's just a parameter
    (λ (list1 list2)
      (cond
        [(empty? list1) empty]
        [else (cons (string-append (first list1) (first list2))
                    (two-list (rest list1) (rest list2)))]))))
 '("1" "2" "3") '("4" "5" "6")) ; here we pass the arguments

=> '("14" "25" "36")
相关问题