多态数据类型的函数 [英] Functions to Polymorphic data types

查看:79
本文介绍了多态数据类型的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

data Foo a 的定义如下:

data Foo a is defined like:

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 - >例如:

How can I define any function from b -> Foo a, for example:

getFoo :: (Show a, Typeable a) => String -> Foo a
getFoo "five" = fiveFoo
getFoo "false" = falseFoo

getFoo 不会与类型检查无法将类型'a'与'Bool'匹配

我唯一感兴趣的是 a 是类 Show 因此我可以使用 getFoo ,例如:

The only thing that I am interested in here is for a to be of class Showso I can use getFoo like:

main = getLine >>= (print . getFoo)


推荐答案

可能你想省略Foo的类型参数。

Perhaps you want to omit the type parameter from 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'

这篇关于多态数据类型的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆