Haskell实现Nonz类型类时r与a类型不匹配如何解决?
错误原因
你当前的类型类定义中,nonz的签名要求支持任意类型的第二个入参a,但(->) r实例对应的函数只能接收r类型的入参,两者类型不匹配才会触发报错。
解决方案1:使用多参数类型类
开启MultiParamTypeClasses扩展,将入参类型也作为类型类的参数,直接绑定两者的类型关系:
{-# LANGUAGE MultiParamTypeClasses #-} class Nonz z a where nonz :: (Eq s, Num s, Show s) => z s -> a -> Maybe s instance Nonz ((->) r) r where nonz f v = let w = f v in if w == 0 then Nothing else Just w main = do print $ nonz (+3) 7 print $ nonz (+4) (-4)
解决方案2:使用关联类型
如果不想使用多参数类型类,可以开启TypeFamilies扩展,通过关联类型绑定容器对应的入参类型:
{-# LANGUAGE TypeFamilies #-} class Nonz z where type Arg z :: * nonz :: (Eq s, Num s, Show s) => z s -> Arg z -> Maybe s instance Nonz ((->) r) where type Arg ((->) r) = r nonz f v = let w = f v in if w == 0 then Nothing else Just w main = do print $ nonz (+3) 7 print $ nonz (+4) (-4)
两种方案都可以正常编译运行,输出结果和你最开始写的普通函数版本完全一致。
内容的提问来源于stack exchange,提问作者bertramscharpf
相关产品推荐
相关产品推荐

