crystal-lang – 水晶中的递归过程

水晶中的递归过程是否可行?

lambda in Ruby这样的东西

我正在尝试在Crystal中做一个y-combinator,就像Ruby一样:

puts -> {
  fact_improver = ->(partial) {
    -> (n) { n.zero? ? 1 : n * partial.(n-1) }
  }
  y = ->(f) {
    ->(x) { f.(->(v) { x.(x).(v) }) }.(
    ->(x) { f.(->(v) { x.(x).(v) }) }
    )
  }
  fact = y.(fact_improver)
  fact = fact_improver.(fact)
  fact.(100)
}.()

上述代码取自Y Not- Adventures in Functional Programming

据我所知,Crystal没有递归过程.但要创建Y组合器,您不需要递归过程.实际上,根据 definition

In functional programming, the Y combinator can be used to formally define recursive functions in a programming language that doesn’t support recursion.

下面是使用recursive types用Crystal编写的Y组合器的示例:

alias T = Int32
alias Func = T -> T
alias FuncFunc = Func -> Func
alias RecursiveFunction = RecursiveFunction -> Func

fact_improver = ->(partial : Func) {
  ->(n : T) { n.zero? ? 1 : n * partial.call(n - 1) }
}

y = ->(f : FuncFunc) {
  g = ->(r : RecursiveFunction) { f.call(->(x : T) { r.call(r).call(x) }) }
  g.call(g)
}

fact = y.call(fact_improver)
fact = fact_improver.call(fact)
fact.call(5) # => 120

更新:可以使用未初始化的关键字在Crystal中创建递归proc:

g = uninitialized Int32 -> Int32
g = ->(n : Int32) { n.zero? ? 1 : n * g.call(n - 1) }
g.call(5) # => 120

感谢@mgarciaisaia的评论.

相关文章
相关标签/搜索