Haskell相当于-rectypes

The*_*nce 6 haskell

允许递归类型的OCaml -rectypes的GHC等价物是多少?我没有在文档中看到一个.它是隐藏的功能吗?

Dan*_*zer 9

遗憾的是,没有一个递归必须通过数据类型.但是,如果你愿意忍受一些头痛,你仍然可以很容易地编写递归类型.

 newtype RecArr b a = RecArr {unArr :: RecArr b a -> b}

 unfold = unArr
 fold   = RecArr
Run Code Online (Sandbox Code Playgroud)

现在我们可以foldunfold我们RecArr一起展示我们对心灵内容的递归.这有点痛苦,因为它是手动的,但完全可行.作为演示,这里是使用fold和编写的y组合器unfold.

 y f = (\x -> f (unfold x x)) $ fold (\x -> f (unfold x x))

 factorial f n = if n == 0 then 1 else n * f (n-1)

 main = print (y factorial 5) -- prints 120
Run Code Online (Sandbox Code Playgroud)