我对幻像类型的使用感到困惑:
type Words = String
type Numbers = Int
data NonPhantom = NP1 Words | NP2 Numbers deriving (Show)
data Phantom a = P1 Words | P2 Numbers deriving (Show)
nonPhantomFunction :: NonPhantom -> Int
nonPhantomFunction r = 100
phantomFunction :: Phantom Numbers -> Int
phantomFunction a = 2001
main = do
print $ nonPhantomFunction (NP1 "sdsdds") --can also pass NP2 here!
print $ phantomFunction (P1 "sdsdsd") --This shouldn't work!?
我希望这段代码NOT能够编译,因为phantomFunction
明确声明了它期望的Phantom
数据类型Numbers
.
但是这样编译好吗?我做错了什么?
最佳答案
data Phantom a = P1 Words | P2 Numbers deriving (Show)
这使得 P1 "aa"
为 Phantom a
形式的任何类型,对于任何 a
,包括 Numbers
.
关于haskell - 幽灵类型困惑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39931404/