在“一侧”调用函数Bifunctor 的值取决于布尔值
如果我有一个 Bifunctor[A,A] bf 实例,则函数 f : A => A 和 Boolean
值 p
:
def calc[A, F[_,_]: Bifunctor](p: Boolean, bf: F[A, A], f: A => A): F[A, A] = {
val BF = implicitly[Bifunctor[F]]
BF.bimap(bf, (a : A) => if (p) f(a) else a, (a : A) => if (!p) f(a) else a)
}
我怎样才能更简洁(和表达)地表达它?基本上,我试图在依赖于某些谓词的双函子(例如Tuple2
)一侧调用函数。如果谓词为 true,我想映射 LHS,如果为 false,则映射 RHS
val t2 = (1, 2)
def add4 = (_ : Int) + 4
calc(true, t2, add4) //should be (5,2)
calc(false, t2, add4) //should be (1,6)
Given that I want to use tuples (as opposed to the more general
Bifunctor
),I seem to be able to use arrows as follows:def calc[A](p: Boolean, bf: (A, A), f: A => A): (A, A)
= (if (p) f.first[A] else f.second[A]) apply bf
If I have an instance of Bifunctor[A,A]
bf, a function f : A => A
and a Boolean
value p
:
def calc[A, F[_,_]: Bifunctor](p: Boolean, bf: F[A, A], f: A => A): F[A, A] = {
val BF = implicitly[Bifunctor[F]]
BF.bimap(bf, (a : A) => if (p) f(a) else a, (a : A) => if (!p) f(a) else a)
}
How can I put this more concisely (and expressively)? Basically I am trying to invoke a function on a side of a bifunctor (e.g. a Tuple2
) dependent on some predicate. If the predicate is true, I want to map the LHS and the RHS if it's false
val t2 = (1, 2)
def add4 = (_ : Int) + 4
calc(true, t2, add4) //should be (5,2)
calc(false, t2, add4) //should be (1,6)
Given that I want to use tuples (as opposed to the more general
Bifunctor
),I seem to be able to use arrows as follows:def calc[A](p: Boolean, bf: (A, A), f: A => A): (A, A)
= (if (p) f.first[A] else f.second[A]) apply bf
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不是那么好:
更好一点:
一些 Haskell,只是为了语言羡慕:
Not all that much nicer:
A little nicer:
Some Haskell, just for the language envy:
这种变化是否Apocalisp 的解决方案有效吗?
注意:我没有使用 scalaz 对此进行测试。
Does this variation on Apocalisp's solution work?
Note: I didn't test this with scalaz.
编辑:修复为返回
(A,A)
而不是A
也许我错过了一些东西,但这不是临时变量的用途吗?使用常规 Scala 元组:
或
Edit: fixed to return
(A,A)
instead ofA
Maybe I'm missing something, but isn't this what temporary variables are for? With a regular Scala tuple:
or