如何解决haskell 和 Validation Applicative
我有一个问题,来自“Haskell Programming from first Principles”一书第 17 章“Applicative”的“Either and Validation Applicative”部分。
我做了以下代码:
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
有效,但如果我将其更改为:
fail4 = fail1a <*> fail2
抛出错误:
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
为什么会这样? fail1a
与 fail1b
相比的唯一区别是在其类型签名中包含类型 Int
而不是 b
..
解决方法
发生这种情况是因为 <*>
的类型为 Applicative f => f (a -> b) -> f a -> f b
。
让我们看看 fail4
的定义:
fail4 :: Validation [Errors] Int
fail4 = fail1b <*> fail2
我们可以推导出 fail1b
和 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)
因此,在这种情况下,Validation [Errors] b
的 fail1b
类型变为 Validation [Errors] (Int -> Int)
。
但是,如果您将 fail1b
替换为 fail1a
,则无法完成:
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
如果将运算符 <*>
替换为 *>
,您可以修复它:
fail4 :: Validation [Errors] Int
fail4 = fail1b *> fail2 -- or fail1a *> fail2
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。