无法构造inifnite类型

时间:2018-06-28 16:34:06

标签: haskell fold

data Prop = a | b | c | d 
      deriving (Show, Eq)

data Wrapper =
      Wtail
      | Wrap prop
      | Mrappe Wrapper Wrapper
      deriving (Show, Eq)


fold_wrap :: (a -> a -> a) -> (Prop -> a) -> a -> Wrapper -> a

fold_wrap v x z (Mrappe l r)   = v ( v(v x z l) v(v x z r) )
fold_wrap v x z (Wrap f)       = x f 
fold_warp v x z (Wtail )       = z

上面的代码出现以下错误:

ghc mast.hs
[1 of 1] Compiling Main             ( mast.hs, mast.o )

mast.hs:13:39: error:
    • Occurs check: cannot construct the infinite type: a ~ Prop -> a
    • In the first argument of ‘v’, namely ‘x’
      In the first argument of ‘v’, namely ‘(v x z l)’
      In the first argument of ‘v’, namely ‘(v (v x z l) v (v x z r))’
    • Relevant bindings include
        z :: a (bound at mast.hs:13:15)
        x :: Prop -> a (bound at mast.hs:13:13)
        v :: a -> a -> a (bound at mast.hs:13:11)
        fold_mast :: (a -> a -> a) -> (Prop -> a) -> a -> Wrapper -> a
          (bound at mast.hs:13:1)
   |
13 | fold_mast v x z (Wrapper l r)  = v ( v(v x z l) v(v x z r) )
   |                                       ^

我看过:

Why does this Haskell code produce the "infinite type" error?

如果我理解正确,我将无法将v函数放入fold_wrap中,因为它将允许无限递归。

方法fold_wrap应该折叠树状结构Wrapper,其中wtail指向预先配置的常数,Wrap有一个值,而Mrappe是是什么使得数据结构像树一样。

我的问题是:

如何避免出现“无法构造无限类型”错误?

1 个答案:

答案 0 :(得分:3)

这看起来不对

fold_wrap v x z (Mrappe l r)   = v ( v(v x z l) v(v x z r) )

v带有两个a参数,而x, z, l则是三个参数。而且x, l的类型不是a。 实际上,x的类型为Prop -> a,将a ~ Prop -> a等同于会导致无效的“无限”类型。

您想在此递归:

fold_wrap v x z (Mrappe l r)   = v (fold_wrap v x z l) (fold_wrap v x z r)