문제

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
도움이 되었습니까?

해결책

Not all that much nicer:

def calc[A, F[_,_]:Bifunctor](p: Boolean, bf: F[A, A], f: A => A): F[A, A] =
   (if (p) (bf :-> (_: A => A)) else ((_:A => A) <-: bf))(f)

A little nicer:

def cond[A:Zero](b: Boolean, a: A) = if (b) a else mzero

def calc[A, F[_,_]:Bifunctor](p: Boolean, bf: F[A, A], f: Endo[A]): F[A, A] =
  cond(p, f) <-: bf :-> cond(!p, f)

Some Haskell, just for the language envy:

calc p = if p then first else second

다른 팁

Does this variation on Apocalisp's solution work?

def calc[A, F[_,_]:Bifunctor](p: Boolean, bf: F[A, A], f: A => A): F[A, A] =
   (if (p) ((_: F[A,A]) :-> f) else (f <-: (_: F[A,A])))(bf)

Note: I didn't test this with scalaz.

Edit: fixed to return (A,A) instead of A

Maybe I'm missing something, but isn't this what temporary variables are for? With a regular Scala tuple:

Some(bf).map(x => if (p) x.copy(_1 = f(x._1)) else x.copy(_2 = f(x._2))).get

or

{ val (l,r) = bf; if (p) (f(l),r) else (l,f(r)) }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top