我有一個型別顯示如下:
newtype WarningAccumulator w a = WarningAccumulator (a,[w])
deriving (Show,Eq)
然后我有一個仿函式和應用程式,如下所示:
instance Functor (WarningAccumulator w) where
fmap :: (a -> b) -> WarningAccumulator w a -> WarningAccumulator w b
fmap f (WarningAccumulator (value, list)) = WarningAccumulator(f value, list)
instance Applicative (WarningAccumulator w) where
pure :: a -> WarningAccumulator w a
pure a = WarningAccumulator (a,[])
(<*>) :: WarningAccumulator w (a -> b) -> WarningAccumulator w a -> WarningAccumulator w b
(<*>) (WarningAccumulator (empty, f)) (WarningAccumulator (value, list)) =
WarningAccumulator (f value, list)
現在它給了我一個錯誤:
The function ‘f’ is applied to one value argument,
but its type ‘[w]’ has none
In the expression: f value
In the first argument of ‘WarningAccumulator’, namely
‘(f value, list)’
我不明白。你能向我解釋一下,然后幫我解決這個問題嗎?
uj5u.com熱心網友回復:
f有 type [w],它不是函式的型別,所以你不能應用value它。你可能是這個意思:
-- (empty, f) changed to (f, empty)
(<*>) (WarningAccumulator (f, empty)) (WarningAccumulator (value, list)) =
WarningAccumulator (f value, list)
然而,這個例子Applicative是不合法的:它不滿足交換律
u <*> pure y = pure ($ y) <*> u
例如:
u :: WarningAccumulator String (Int -> Int)
u = WarningAccumulator (( 1), ["warning"])
y :: Int
y = 2
u <*> pure y == WarningAccumulator (3, [])而pure ($ y) <*> u == WarningAccumulator (3, ["warning"]).
您可能想要連接警告而不是丟棄您命名的內容empty(可能不為空):
(<*>) (WarningAccumulator (f, xs)) (WarningAccumulator (value, ys)) =
WarningAccumulator (f value, xs <> ys)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/517111.html
標籤:哈斯克尔
