【问题标题】:Scheme: Lambda Recursion: Combining two lists elements by elements方案:Lambda 递归:按元素组合两个列表元素
【发布时间】:2014-01-23 10:00:00
【问题描述】:

我刚开始学习 Scheme,我们开始学习匿名函数。我们正在学习如何递归 lambda,我了解递归单变量函数,例如查找阶乘,但是对于像下面这样的函数,我将如何做到这一点?

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

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

【问题讨论】:

  • 我的错,我说得不够清楚。我们要做的就是将该代码转换为使用 lambda 的代码。我们正在学习 lambda 递归。
  • 以上是已经使用lambda,只是它隐藏在一些语法糖后面。我用等效代码更新了我的答案以反映这一点
  • 哦,我现在看到了,谢谢!只是出于好奇,是否有可能使整个事情变成 lambda,比如在不定义任何东西的情况下使这个函数工作。
  • 是的,可以仅使用匿名函数 (lambdas) 来实现递归。查看Y-Combinator
  • 好的,我会读一读。如果不是太多工作介意对我拥有的功能进行操作,以便我可以参考吗? :)

标签: scheme


【解决方案1】:

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

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

也许有些cmets会说清楚:

(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

更新

作为 cmets 中提到的概念的证明,以下是使用 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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 2016-01-25
    • 2021-07-12
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多