gpt4 book ai didi

haskell - 应用左星测序算子和右星测序算子预期做什么?

转载 作者:行者123 更新时间:2023-12-02 10:30:30 25 4
gpt4 key购买 nike

我查了一下实现,它更加神秘:

-- | Sequence actions, discarding the value of the first argument.
(*>) :: f a -> f b -> f b
a1 *> a2 = (id <$ a1) <*> a2
-- This is essentially the same as liftA2 (flip const), but if the
-- Functor instance has an optimized (<$), it may be better to use
-- that instead. Before liftA2 became a method, this definition
-- was strictly better, but now it depends on the functor. For a
-- functor supporting a sharing-enhancing (<$), this definition
-- may reduce allocation by preventing a1 from ever being fully
-- realized. In an implementation with a boring (<$) but an optimizing
-- liftA2, it would likely be better to define (*>) using liftA2.

-- | Sequence actions, discarding the value of the second argument.
(<*) :: f a -> f b -> f a
(<*) = liftA2 const

我什至不明白为什么 <$值得在类型类中占有一席之地。看起来有一些共享增强效果fmap . const可能没有,a1可能没有“完全实现”。这与 Applicative 的含义有何关系?排序运算符?

最佳答案

这些运算符对两个应用操作进行排序,并提供箭头指向的操作的结果。例如,

> Just 1 *> Just 2
Just 2

> Just 1 <* Just 2
Just 1

编写解析器组合器的另一个例子是

brackets p = char '(' *> p <* char ')'

这将是一个匹配 p 的解析器包含在括号中并给出解析结果 p .

事实上,(*>)(>>) 相同但只需要 Applicative约束而不是 Monad约束。

I don't even understand why does <$ deserve a place in a typeclass.

答案由 the Functor documentation 给出:(<$)有时可以比默认的 fmap . const 更有效的实现.

How is that related to the meaning of Applicative sequencing operators?

(<$) 的情况下更高效,您希望在 (*>) 的定义中保持该效率.

关于haskell - 应用左星测序算子和右星测序算子预期做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45663520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com