haskell *>序列运算符 [英] haskell *> sequencing operator

查看:63
本文介绍了haskell *>序列运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题答案来自以下位置,我有一个问题: haskell或验证适用

I have a question arising from the answer to my question at: haskell Either and Validation Applicative

我的代码张贴在这里.

它涉及到使用 *> 排序运算符而不是< *> 应用运算符.

It concerns the use of the *> sequencing operator instead of the <*> applicative operator.

基于 https://hackage.haskell.org/package/base-4.15.0.0/docs/Control-Applicative.html#v:-42--62- ,我了解*> 对动作进行排序,丢弃第一个参数的值.因此,对于我的代码,我尝试了 fail6 = fail2 *>成功,它可以工作,但是不应该工作,因为第一个参数的值,即fail2,应该被丢弃.为什么 fail6 有效?

Based on the explanation at https://hackage.haskell.org/package/base-4.15.0.0/docs/Control-Applicative.html#v:-42--62-, I understand that *> sequences actions, discarding the value of the first argument. So for my code, I've tried fail6 = fail2 *> success, which works, but it's not supposed to work because the value of the first argument, namely fail2, should be discarded. Why does fail6 work?

fail6 的输出为 Failure [MooglesChewedWires,StackOverflow] .

推荐答案

丢弃结果"表示应用程序的结果.因此,对于 Either 来说,这意味着 Right y .因此,(*>)等同于:

With "discard the result", it means the result of an applicative. So for an Either that means a Right y. (*>) is thus equivalent to:

(*>) :: Applicative f => f a -> f b -> f b
(*>) f g = liftA2 (const id) f g

或另一种形式:

(*>) :: Applicative f => f a -> f b -> f b
(*>) f g = (const id) <$> f <*> g

它因此运行两个动作并返回第二个结果,但这在" Applicative 上下文"中.

It thus runs the two actions and returns the second result, but this in the "Applicative context".

例如,对于 Either 的任何实现,该实现都为:

For example for an Either, this is implemented as:

instance Applicative (Either a) where
    pure = Right
    Left e <*> _ = Left e
    _ <*> Left e = Left e
    Right f <*> Right x = Right (f x)

因此,这意味着(*>) Either 的实现方式为:

This thus means that (*>) is implemented for an Either as:

-- (*>) for Either
(*>) :: Either a b -> Either a c -> Either a c
Left x *> _ = Left x
_ *> Left x = Left x
Right _ *> Right x = Right x

或等价物:

-- (*>) for Either
(*>) :: Either a b -> Either a c -> Either a c
Left x *> _ = Left x
_ *> x = x

如果第一个操作数是 Right…,它将返回第二个操作数,如果第一个操作数是 Left x ,则将返回 Left x.

If the first operand is thus a Right …, it will return the second operand, if the first operand is Left x, it will return Left x.

这篇关于haskell *&gt;序列运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆