数据构造函数 - 相同类型

时间:2014-11-01 01:02:48

标签: haskell

给出以下数据类型:

data JoinList m a = Empty
                  | Single m a
                  | Append m (JoinList m a) (JoinList m a)
    deriving (Eq, Show)

使用ghci,我做了:

*JoinList> :t Single 5 3
Single 5 3 :: (Num m, Num a) => JoinList m a

为什么这里需要两种Num类型?由于这两种类型都是Num,为什么我们不能拥有:

Single 5 3 :: (Num m) => JoinList m m

1 个答案:

答案 0 :(得分:5)

这不是一个给定的他们是同一类型。

您允许类型在JoinList的定义中有所不同,并且您没有断言5和3在类型签名中是相同的Num。

GHCi, version 7.8.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> :l joinlist.hs
[1 of 1] Compiling JoinList         ( joinlist.hs, interpreted )
Ok, modules loaded: JoinList.
Prelude> :t Single 5 3
Single 5 3 :: (Num a, Num m) => JoinList m a
Prelude> let same = Single 5 3 :: Num a => JoinList a a
Prelude> :t same
same :: Num a => JoinList a a

因为文字是多态Num值,所以它们可能是两种不同的具体类型。

Prelude> let diff = Single 5 3 :: JoinList Int Float
Prelude> diff
Single 5 3.0
Prelude> :t diff
diff :: JoinList Int Float