編寫用於接收兩個列表作爲參數遞歸函數是從執行單參數的功能沒有什麼不同:只處理又和提前超過兩個列表的每個元素,根據所要解決問題的規則。事實上,您發佈的代碼沒有任何問題(假設兩個列表的長度相同)。下面是執行它的結果:
(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
UPDATE
至於什麼在評論中提到的一個概念證明,這裏的如何使用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")
我的不好,我沒有讓自己清楚。我們必須做的是將該代碼轉換爲使用lambda的代碼。我們正在學習lambda遞歸。 – user3225528
以上是_already_使用'lambda',這只是它隱藏了一點語法糖後面。我用等價代碼更新了我的答案,以反映這 –
哦,我現在看到它,謝謝!出於好奇,是否有可能使整個事情lambda,就像使這個功能沒有任何定義的工作。 – user3225528