爲了幫助我學習Applicative Functors和Functors,我認爲使用類型Functor
和Applicative
來實現Either
將會很有趣。很明顯,我可以繼續閱讀代碼,但是我發現嘗試自己實現以更好地理解事物更有用。試圖執行數據。要麼
僅供參考我想實現這個演示http://applicative-errors-scala.googlecode.com/svn/artifacts/0.6/chunk-html/index.html
反正結果的哈斯克爾版本,這是我迄今爲止
data Validation a b = Success a | Failure b deriving (Show, Eq)
instance Functor (Validation a) where
fmap f (Failure x) = Failure x
fmap f (Success x) = Success (f x)
但每當我嘗試使用ghci
運行此我剛剛收到以下錯誤消息: -
[1 of 1] Compiling Main (t.hs, interpreted)
t.hs:5:35:
Couldn't match type `b' with `a1'
`b' is a rigid type variable bound by
the type signature for
fmap :: (a1 -> b) -> Validation a a1 -> Validation a b
at t.hs:4:5
`a1' is a rigid type variable bound by
the type signature for
fmap :: (a1 -> b) -> Validation a a1 -> Validation a b
at t.hs:4:5
Expected type: a
Actual type: b
In the return type of a call of `f'
In the first argument of `Success', namely `(f x)'
In the expression: Success (f x)
t.hs:5:37:
Couldn't match type `a' with `a1'
`a' is a rigid type variable bound by
the instance declaration at t.hs:3:30
`a1' is a rigid type variable bound by
the type signature for
fmap :: (a1 -> b) -> Validation a a1 -> Validation a b
at t.hs:4:5
In the first argument of `f', namely `x'
In the first argument of `Success', namely `(f x)'
In the expression: Success
我不確定爲什麼這是,任何人都可以幫忙嗎?
唉唉我明白了,謝謝,我假定'數據驗證A B =失敗一個|成功b導出(Show,Eq)'也是正確的。謝謝! – djhworld
@djworld:是的。這與類型變量的名稱和構造函數交換的順序是一樣的。 – hammar
@djhworld:現在你也明白了爲什麼在''b'','Left'代表失敗的情況下(不僅僅因爲它不是「正確的」結果)。 –