gpt4 book ai didi

haskell - 多态数据类型的函数

转载 作者:行者123 更新时间:2023-12-04 22:29:16 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com