【发布时间】:2016-08-25 21:01:35
【问题描述】:
数据Foo a 定义如下:
data Foo a where
Foo :: (Typeable a, Show a) => a -> Foo a
-- perhaps more constructors
instance Show a => Show (Foo a) where
show (Foo a) = show a
在某些情况下:
fiveFoo :: Foo Int
fiveFoo = Foo 5
falseFoo :: Foo Bool
falseFoo = Foo False
如何定义b -> Foo a中的任何函数,例如:
getFoo :: (Show a, Typeable a) => String -> Foo a
getFoo "five" = fiveFoo
getFoo "false" = falseFoo
这里getFoo 不使用Couldn't match type ‘a’ with ‘Bool’ 进行类型检查。
我在这里唯一感兴趣的是a 属于Show,所以我可以使用getFoo,例如:
main = getLine >>= (print . getFoo)
【问题讨论】:
标签: haskell polymorphism gadt existential-type