jek*_*339 2 haskell functional-programming
我有一些我想要打印的数据(有些是Maybe,有些则不是),我正在尝试创建一个通用的showField函数,如下所示:
showField :: (Show a) => a -> Text
showField x
| isJust x = Text.pack $ show $ fromJust x
| isNothing x = "None"
| otherwise = Text.pack $ show x
Run Code Online (Sandbox Code Playgroud)
这是一个严格的类型错误:
• Couldn't match expected type ‘Maybe a0’ with actual type ‘a’
‘a’ is a rigid type variable bound by
the type signature for:
showField :: forall a. Show a => a -> Text
at /data/users/jkozyra/fbsource/fbcode/experimental/jkozyra/hs/holdout_cleanup/HoldoutReaper.hs:244:18
• In the first argument of ‘isNothing’, namely ‘x’
In the expression: isNothing x
In a stmt of a pattern guard for
an equation for ‘showField’:
isNothing x
Run Code Online (Sandbox Code Playgroud)
我一般都明白这个错误,但我不明白是否有办法实现我想要的.我也尝试过模式匹配而不是守卫,但也不能完全解决问题.我可以用这种格式构建一些可行的东西吗?
ram*_*ion 11
看起来你正在尝试构建一个adhoc多态函数 - 一个函数,其定义根据其类型而变化.
参数化多态函数对所有数据类型执行相同的操作:
both :: a -> (a,a)
both a = (a,a)
Run Code Online (Sandbox Code Playgroud)
在Haskell中,adhoc多态性是使用类型类实现的:
class ShowField a where
showField :: a -> Text
instance Show a => ShowField (Maybe a) where
showField Nothing = "None"
showField (Just a) = Text.pack $ show a
Run Code Online (Sandbox Code Playgroud)
但是,没有办法为类型类定义"除了Maybe a之外的所有其他类型"的实例,因此您只需要为实际关注的类型定义实例:
class ShowField Int where
showField = Text.pack . show
class ShowField Float where
showField = Text.pack . show
Run Code Online (Sandbox Code Playgroud)
您可以使用-XDefaultSignatures
以下方法减少样板:
class ShowField' a where
showField :: a -> Text
default showField :: Show a => a -> Text
showField = Text.pack . show
instance ShowField' Int where
instance ShowField' Float where
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
209 次 |
最近记录: |