recursion - 将 Y-Combinator 应用于 Clojure 中具有两个参数的递归函数?

标签 recursion clojure lisp y-combinator

在 Clojure 中为单个参数函数(例如阶乘或斐波那契)执行 Y 组合器有详细记录: http://rosettacode.org/wiki/Y_combinator#Clojure

我的问题是 - 对于像这个 getter 这样的双参数函数,你如何做到这一点?

(这里假设我想递归地解决这个问题,而这个非惯用的 clojure 代码是出于其他原因故意存在的)

[非 y 组合器版本]

(defn get_ [n lat]
    (cond
      (empty? lat) ()
        (= 0 (- n 1)) (first lat)
        true (get_ (- n 1) (rest lat))))

(get_ 3 '(a b c d e f g h i j))

最佳答案

args 的数量不会改变任何东西,因为 argsapply 的。你只需要改变get_的结构:

(defn get_ [f]
  (fn [n lat]
    (cond
      (empty? lat) ()
      (= 1 n) (first lat)
      :else (f (dec n) (next lat)))))

(defn Y [f]
  ((fn [x] (x x))
   (fn [x]
     (f (fn [& args]
          (apply (x x) args))))))
user=> ((Y getf) 3 '(a b c d e f g h i j))
c

关于recursion - 将 Y-Combinator 应用于 Clojure 中具有两个参数的递归函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3483077/

相关文章:

recursion - F# 模式匹配和递归与循环和 if..then 用于解析嵌套结构

python - OSX 不断报告 python 意外退出并中止 python

recursion - 方案:给定列表的列表和排列,排列

clojure - 部署后在 ring/compjure 应用程序启动时执行函数

clojure - 在我自己的数据结构中递增数字时 clojure 中的不变性,从常见的 lisp 可变性到 clojure 不变性

javascript - 我应该如何从 Java 应用程序运行 NodeJS?

format - 格式化为 base 16 的 float

c++ - 将子字符串传递给函数

javascript - 延迟迭代对象

lisp - 从列表中删除元素