haskell - 多态数据类型的函数

标签 haskell polymorphism gadt existential-type

数据 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)

最佳答案

也许您想省略 Foo 中的类型参数。

data Foo where
  Foo :: (Typeable a, Show a) => a -> Foo

instance Show Foo where
  show (Foo a) = show a

fiveFoo :: Foo
fiveFoo = Foo (5 :: Int) -- (Foo 5) doesn't work because of ambiguity

falseFoo :: Foo
falseFoo = Foo False

getFoo :: String -> Foo
getFoo "five" = fiveFoo
getFoo "false" = falseFoo

print $ getFoo "five" -- prints '5'
print $ getFoo "false" -- prints 'False'

关于haskell - 多态数据类型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39143379/

相关文章:

parsing - F# 解析器组合器

list - 在不使用 sortBy 的情况下按第二个元素对元组列表进行排序

performance - 找到所有后续元素之间的最大差异

c++ - 问题向下转换到子类,多态性不起作用

haskell - 以类型安全的方式对 POST API 建模

haskell - 对受约束的 GADT 记录使用记录更新语法

haskell - 如何返回从列表前面删除指定数量元素的列表

java - 泛型多态混淆?

c++ - 找出父类型 vector 元素的子类型

haskell - Haskell 中嵌套对是个好主意吗