Reputation: 491
I have a question arising from the section "Either and Validation Applicative" of Chapter 17 "Applicative" of the book "Haskell Programming from first principles".
I did the following code:
data Validation err a =
Failure err
| Success a
deriving (Eq, Show)
data Errors =
DividedByZero
| StackOverflow
| MooglesChewedWires
deriving (Eq, Show)
instance Functor (Validation e) where
fmap _ (Failure x) = Failure x
fmap f (Success y) = Success (f y)
instance Monoid e =>
Applicative (Validation e) where
pure = Success
Failure e1 <*> Failure e2
= Failure (e1 <> e2)
Failure e <*> _ = Failure e
_ <*> Failure e = Failure e
Success f <*> Success r = Success (f r)
success :: Validation [Errors] Int
success = Success (+1)
<*> Success (1::Int)
fail0 :: Validation [Errors] Int
fail0 = Success (+1)
<*> Failure [StackOverflow::Errors]
-- this doesn't work:
fail1a :: Validation [Errors] Int
fail1a = Failure [StackOverflow::Errors]
<*> Success (1)
-- this works:
fail1b :: Validation [Errors] b
fail1b = Failure [StackOverflow::Errors]
<*> Success (1::Int)
fail2 :: Validation [Errors] Int
fail2 = Failure [MooglesChewedWires]
<*> Failure [StackOverflow::Errors]
fail3 :: Validation [Errors] Int
fail3 = (Failure [StackOverflow::Errors]
<*> Success (+1)) <*> (Failure [MooglesChewedWires]
<*> Failure [StackOverflow::Errors])
fail4 :: Validation [Errors] Int
fail4 = fail1b <*> fail2
fail4 = fail1b <*> fail2
works, but if I changed it to:
fail4 = fail1a <*> fail2
An error is thrown:
Couldn't match type ‘Int’ with ‘Int -> Int’
Expected type: Validation [Errors] (Int -> Int)
Actual type: Validation [Errors] Int
• In the first argument of ‘(<*>)’, namely ‘fail1a’
In the expression: fail1a <*> fail2
Why does this happen? The only difference that fail1a
has compared with fail1b
, is the inclusion of type Int
in its type signature instead of b
..
Upvotes: 0
Views: 204
Reputation: 875
This happens because <*>
has type Applicative f => f (a -> b) -> f a -> f b
.
Let's look at definition of fail4
:
fail4 :: Validation [Errors] Int
fail4 = fail1b <*> fail2
We can deduce expected types of fail1b
and fail2
:
fail4 :: Validation [Errors] Int
fail4 = fail1b <*> fail2
+----+ +---+
v v
expected: f (a -> b) f a (Applicative f)
v v
real: Validation [Errors] b Validation [Errors] Int
v
Validation [Errors] (Int -> c)
v
Validation [Errors] (Int -> Int)
So, in this case type Validation [Errors] b
of fail1b
turn to Validation [Errors] (Int -> Int)
.
However if you replace fail1b
to fail1a
it can't be done:
fail4 :: Validation [Errors] Int
fail4 = fail1a <*> fail2
+----+ +---+
v v
expected: f (a -> b) f a (Applicative f)
(error) v
real: Validation [Errors] Int Validation [Errors] Int
You can fix it if you replace operator <*>
to *>
:
fail4 :: Validation [Errors] Int
fail4 = fail1b *> fail2 -- or fail1a *> fail2
Upvotes: 3