How can I combine a tuple of values ​​with a tuple of functions?

I have scalaZ.

I have (A, B) and (A => C, B => D) , I would like to get (C, D) simple and understandable way.

I feel that there is something I can do with applications, but I can not find the right methods.

+6
source share
5 answers

Edit

At first it did not work out that the OP has a set of functions. In that case, as suggested in the comments, this should work:

 val in = ("1", 2) val fnT = ((s: String) => s.toInt, (i: Int) => i.toString) val out = (in.bimap[Int, String] _).tupled(fnT) 

Old

If you have two functions and want to apply them to a tuple, you should be able to:

 import scalaz._ import Scalaz._ val in = ("1", 2) val sToi = (s: String) => s.toInt val iTos = (i: Int) => i.toString val out = sToi <-: in :-> iTos // or val out1 = in.bimap(sToi, iTos) // or val out2 = (sToi *** iTos)(in) 
+4
source

Arrows? Sort of:

(f *** g)(a, b)

http://eed3si9n.com/learning-scalaz/Arrow.html

+3
source

I do not find scalaz more readable. What is wrong with defining your own function.

 def biFunc(valTup:(A,B), funTup:((A)=>C,(B)=>D)):(C,D) = (funTup._1(valTup._1), funTup._2(valTup._2)) 
+1
source

I agree with Lionel Port, but you can make it more readable via:

 case class BiFun[A,B,C,D](f1:A=>C, f2: B=>D){ def applyTo(a: (A,B)) = (f1(a._1), f2(a._2)) } object BiFun{ implicit def toBiFun(a: (A=>C, B=>D)) = BiFun(a._1, a._2) } 

used as:

 import BiFun._ val ab = (A(1), B(2)) val ac = (x: A) => C(x.i+2) val bd = (x: B) => D(x.i+2) val bifn = (ac, bd) bifn applyTo ab 

So, in the end you get funTuple applyTo tuple and get top-level readability

+1
source

Writing this method might be the best choice:

 def bimap[A,B,C,D](vals:(A, B), funcs:(A=>C, B=>D)):(C,D) = { val ((func1, func2), (val1, val2)) = funcs -> vals func1(val1) -> func2(val2) } 

And if you do this a lot, you can even improve the class of tuples:

 implicit class EnhancedTuple2[A, B](val vals: (A, B)) extends AnyVal { def bimap[C, D](funcs: (A=>C, B=>D)) = { val ((func1, func2), (val1, val2)) = funcs -> vals func1(val1) -> func2(val2) } } 

So you can:

 val func1: Int => Int = x => x * x val func2: Int => String = x => x.toString val tupledFuncs = func1 -> func2 (1, 2).bimap(tupledFuncs) 
0
source

Source: https://habr.com/ru/post/982711/


All Articles