我对Haskell很陌生。我正在尝试为不同的容器重载自定义函数“ myadd”。我的理解是,您必须通过课堂来做到这一点。这是我尝试的:
class Addition a where
myadd :: a -> a -> a
instance Addition Int where
myadd a b = a + b
instance Addition Maybe where
myadd (Just a) (Just b) = Just (a + b)
main = do
let a = 3 :: Int
let b = 4
let c = myadd a b
print c
let d = (Just a)
let e = (Just b)
let f = myadd d e
print f
但我得到以下错误:
test.hs:7:19: error:
? Expecting one more argument to ‘Maybe’
Expected a type, but ‘Maybe’ has kind ‘* -> *’
? In the first argument of ‘Addition’, namely ‘Maybe’
In the instance declaration for ‘Addition Maybe’
最佳答案
Addition
具有类型* -> *
,因此Addition
的参数必须为类型*
。 Maybe
具有种类* -> *
。您需要将其他类型参数传递给Maybe
,以使其具有类型*
。
instance Addition (Maybe a)
问题在于,对于任意
Maybe a
,Addition
都不是a
的实例,而对于已经是a
实例的Addition
而言,它仅是a
的实例。您可以这样指定Addition
是myadd
的实例的要求:instance Addition a => Addition (Maybe a)
同样,您的实现应使用
+
而不是:instance Addition a => Addition (Maybe a) where
myadd (Just a) (Just b) = Just (myadd a b)