12

Applicative FunctorとEitherFunctor を学ぶために、 が型クラス と でどのように実装されているかを見るのはとても楽しいと思いました。もちろん、先に進んでコードを読むこともできますが、物事をよりよく理解するために、自分で物事を実装してみる方が便利だと思います。FunctorApplicative

参考までに、このプレゼンテーションの結果の Haskell バージョンを実装しようとしています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

これがなぜなのかよくわかりません。誰か助けてもらえますか?

4

1 に答える 1

13

Functorインスタンスをパーツで機能させようとしていますSuccessが、これは通常のことですが、型パラメーターの順序のために、Failure代わりにパーツの型で定義されています。

あなたはそれを次のように定義したので

data Validation a b = Success a | Failure b

instance Functor (Validation a) where
    ...

これは、 の実装にfmapはタイプが必要であることを意味します(x -> y) -> Validation a x -> Validation a y。ただし、2 番目の型変数はFailureケース用であるため、これは型チェックを行いません。

代わりに、ケースの型変数をSuccess最後のものにする必要があります。

data Validation b a = Success a | Failure b
于 2011-08-19T12:08:55.577 に答える