2011-08-19 25 views
12

爲了幫助我學習Applicative Functors和Functors,我認爲使用類型FunctorApplicative來實現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 

我不確定爲什麼這是,任何人都可以幫忙嗎?

回答

13

你正在努力使在Success的一部分,這是做正常的事情了Functor情況下工作,但因爲你的類型參數的順序也正在對在Failure一部分,而不是類型定義。

既然你已經將它定義爲

data Validation a b = Success a | Failure b 

instance Functor (Validation a) where 
    ... 

這意味着你的fmap實施應該有類型(x -> y) -> Validation a x -> Validation a y。但由於第二種類型的變量是針對Failure的情況,因此不會進行類型檢查。

要用於Success情況下,類型變量,而不是最後一個:

data Validation b a = Success a | Failure b 
+0

唉唉我明白了,謝謝,我假定'數據驗證A B =失敗一個|成功b導出(Show,Eq)'也是正確的。謝謝! – djhworld

+1

@djworld:是的。這與類型變量的名稱和構造函數交換的順序是一樣的。 – hammar

+5

@djhworld:現在你也明白了爲什麼在''b'','Left'代表失敗的情況下(不僅僅因爲它不是「正確的」結果)。 –