将Scheme闭包定义函数转换为Haskell

时间:2015-05-25 21:50:24

标签: haskell recursion types scheme closures

以下程序,用Scheme编写,

> eat 
#{procedure 9165 eat}
> (eat '())
#{procedure 9166 (unnamed in eat)}
> ((eat '()) 1)
#{procedure 9166 (unnamed in eat)}
> (((((eat '()) 1) 2) 3) 4)
#{procedure 9166 (unnamed in eat)}
> ((((((eat '()) 1) 2) 3) 4) 'vomit)
(1 2 3 4) 

可以通过以下方式调用:

set!

因为没有突变,例如。 eat xs x = if x == "vomit" then reverse xs else eat (x:xs) -- Couldn't match expected type ‘[[Char]]’ -- with actual type ‘[Char] -> [[Char]]’ -- Probable cause: ‘eat’ is applied to too few arguments -- In the expression: eat (x : xs) -- In the expression: -- if x == "vomit" then reverse xs else eat (x : xs) ,并且使用递归传递状态我认为在Haskell中编写这将是微不足道的:

{{1}}

我错过了一些明显的东西,还是只是不可能?

1 个答案:

答案 0 :(得分:9)

由于你有一个递归类型,你需要明确声明它:

data T a = L [a] | F (a -> T a)

(+>) (F f) = f
unL  (L x) = x

eat xs x = if x == "vomit" then L $ reverse xs else F $ eat (x:xs)

eaten = unL $ eat [] "x" +> "y" +> "z" +> "vomit"
  

*主>吃了       [ “X”, “Y”, “Z”]

定义

eaten1 = eat [] "x" +> "y" 

eaten2 = eaten1 +> "z" +> "vomit"

也有效:

  

*主> unL $ eaten1 +> “呕吐”
      [“x”,“y”]
      *主> unL $ eaten2
      [ “X”, “Y”, “Z”]