How to flat nest tuple parameter in function? - scala

I have a function g which need parameter (Int, (Int, Int)) => Int, and a flat function f0 (Int, Int, Int) => Int
I want to construct a function ft which can flat parameters of g to f0.
Here is the example:
val f0: ((Int, Int, Int)) => Int = (x: (Int, Int, Int)) => {
x._1 + x._2 + x._3
}
def g(f: ((Int, (Int, Int))) => Int): Int = f(1,(2,3))
def ft(f: ((Int, Int, Int)) => Int): ((Int, (Int, Int))) => Int = (p: (Int, (Int, Int))) => {
f(p._1, p._2._1, p._2._2)
}
// invoke it
g(ft(f0))
But I have several functions of nested tuples, and I don't want to transform each manually. For example, ((Int, Int), (Int, Int)) => Int to (Int, Int, Int, Int) => Int
Here said it could use shapeless
Then the new function would like
import shapeless._
import ops.tuple.FlatMapper
trait LowPriorityFlatten extends Poly1 {
implicit def default[T] = at[T](Tuple1(_))
}
object flatten extends LowPriorityFlatten {
implicit def caseTuple[P <: Product](implicit lfm: Lazy[FlatMapper[P, flatten.type]]) =
at[P](lfm.value(_))
}
def ft(f: ((Int, Int, Int)) => Int): ((Int, (Int, Int))) => Int = (p: (Int, (Int, Int))) => {
val a: (Int, Int, Int) = flatten(p).asInstanceOf[(Int, Int, Int)]
f(a)
}
Code above has two problem:
how to define function ft[A, B, C](f: A => C): B where A is a flatten type of B ?
flatten(p) will product type FlatMapper.this.Out and miss the type, so I use asInstanceOf to cast type here.
So, How to write a function to flatten any kind of nested tuple in a parameter?

The following code works in Scala 3:
scala> type Flat[T <: Tuple] <: Tuple = T match
| case EmptyTuple => EmptyTuple
| case h *: t => h match
| case Tuple => Tuple.Concat[Flat[h], Flat[t]]
| case _ => h *: Flat[t]
|
scala> def flat[T <: Tuple](v: T): Flat[T] = (v match
| case e: EmptyTuple => e
| case h *: ts => h match
| case t: Tuple => flat(t) ++ flat(ts)
| case _ => h *: flat(ts)).asInstanceOf[Flat[T]]
def flat[T <: Tuple](v: T): Flat[T]
scala> def ft[A <: Tuple, C](f: Flat[A] => C): A => C = a => f(flat(a))
def ft[A <: Tuple, C](f: Flat[A] => C): A => C
scala> val f0: ((Int, Int, Int)) => Int = x => x._1 + x._2 + x._3
scala> def g0(f: ((Int, (Int, Int))) => Int): Int = f(1,(2,3))
scala> g0(ft(f0))
val res0: Int = 6
Edit: Add scala2's version:
import shapeless._
import ops.tuple.FlatMapper
import syntax.std.tuple._
trait LowPriorityFlat extends Poly1 {
implicit def default[T] = at[T](Tuple1(_))
}
object Flat extends LowPriorityFlat {
implicit def caseTuple[P <: Product](implicit fm: FlatMapper[P, Flat.type]) =
at[P](_.flatMap(Flat))
}
type F[A, B] = FlatMapper.Aux[A, Flat.type, B]
def flatTup[T <: Product](t: T)(implicit lfm: FlatMapper[T, Flat.type]): lfm.Out =
FlatMapper[T, Flat.type].apply(t)
def flatFun[A <: Product, B <: Product, C](f: B => C)
(implicit lfm: F[A, B]): A => C =
a => f(flatTup(a))
val f0: ((Int, Double, Int, Double)) => Double = { case(i1, d1, i2, d2) => (i1 + i2) / (d1 + d2) }
def g0(f: (((Int, Double), (Int, Double))) => Double): Double = f((1, 2.0), (3, 4.0))
val r0 = g0(flatFun(f0))

Related

How to define a lift function in Scala

Can someone help me, how to define this function:
def lift[A, B, T](op: (T,T) => T)(f: A => T, g: B => T): (A,B) => T = /* ... */
Perhaps
def lift[A, B, T](op: (T,T) => T)(f: A => T, g: B => T): (A,B) => T =
(a: A, b: B) => op(f(a), g(b))
which gives
def op(a: Int, b: Int): Int = a + b
def f(x: String): Int = x.toInt
def g(x: List[String]): Int = x.length
lift(op)(f,g)("41", List("2"))
// Int = 42

How to combine two tuples with compatible types?

Suppose I have two tuples, the first is a tuple of values with type (V1, V2, .., Vn),
the second is a tuple of functions with type (V1 => V1, V2 => V2, .., Vn => Vn).
Now I want to combine the two tuples as (f1(v1), v2(v2), .., fn(vn)) with type (V1, V2, .., Vn).
scala> val values = (1, 2.0, "3")
val values: (Int, Double, String) = (1,2.0,3)
scala> val funs = ((i: Int) => 2 * i, (f: Double) => 2 * f, (s: String) => s * 2)
val funs: (Int => Int, Double => Double, String => String) = ..
scala> val res = ??? // (2, 4.0, "33")
I have no idea how to get this in scala 3.0 (i.e. dotty).
EDIT: I look into the source code of shapeless and got a (partial work) solution:
scala> trait Zip[V <: Tuple, F <: Tuple]{ type R <: Tuple; def apply(v: V, f: F): R }
scala> given Zip[Unit, Unit]{ type R = Unit; def apply(v: Unit, f: Unit): Unit = () }
scala> given [Hv, Hr, V <: Tuple, F <: Tuple](given z: Zip[V, F]): Zip[Hv *: V, (Hv => Hr) *: F] = new Zip {
| type R = Hr *: z.R
| def apply(v: Hv *: V, f: (Hv => Hr) *: F): R = {
| f.head(v.head) *: z.apply(v.tail, f.tail)
| }
| }
scala> val values = (1, 2.0, "3")
val values: (Int, Double, String) = (1,2.0,3)
scala> val funs = ((i: Int) => 2 * i, (f: Double) => 2 * f, (s: String) => s * 2)
val funs: (Int => Int, Double => Double, String => String) = ..
scala> def apply[V <: Tuple, F <: Tuple](v: V, f: F)(given z: Zip[V, F]): z.R = z.apply(v, f)
def apply[V <: Tuple, F <: Tuple](v: V, f: F)(given z: Zip[V, F]): z.R
scala> apply(values, funs)
val res0:
Zip[(Int, Double, String), (Int => Int, Double => Double, String => String)]#R = (2,4.0,33)
scala> val res: (Int, Double, String) = apply(values, funs)
1 |val res: (Int, Double, String) = apply(values, funs)
| ^^^^^^^^^^^^^^^^^^^
|Found: ?1.R
|Required: (Int, Double, String)
|
|where: ?1 is an unknown value of type Zip[(Int, Double, String), (Int => Int, Double => Double, String => String)]
I do not known why the return of apply method lost its type.
why the return of apply method lost its type
This is because you lost type refinement (this behavior is similar in Scala 2 and Dotty).
The code
given [Hv, Hr, V <: Tuple, F <: Tuple](given z: Zip[V, F]): Zip[Hv *: V, (Hv => Hr) *: F] = new Zip {
...
should be
given [Hv, Hr, V <: Tuple, F <: Tuple](given z: Zip[V, F]): (Zip[Hv *: V, (Hv => Hr) *: F] { type R = Hr *: z.R }) = new Zip[Hv *: V, (Hv => Hr) *: F] {
...
or with Aux pattern
given [Hv, Hr, V <: Tuple, F <: Tuple](given z: Zip[V, F]): Zip.Aux[Hv *: V, (Hv => Hr) *: F, Hr *: z.R] = new Zip[Hv *: V, (Hv => Hr) *: F] {
...
Tested in 0.21.0-RC1.
This seems to do the trick
val res = List(Range(0, values.productArity).map(n => {
val arg = values.productElement(n)
val f = funs.productElement(n).asInstanceOf[(arg.type) => arg.type]
f.apply(arg)
})).map {
case Vector(a, b, c) => Tuple3(a, b, c)
}.head
zipApply from shapeless would maintain type safety, for example
import shapeless.syntax.std.tuple._
val values = (1, 2.0, "3")
val funs = ((i: Int) => 2 * i, (f: Double) => 2 * f, (s: String) => s * 2)
funs zipApply values
outputs
res0: (Int, Double, String) = (2,4.0,33)
however trying with val values = ("1", "2.0", "3") would give compile-time error.

Scala + Shapeless abstract over curried function

I'm trying to figure out how to abstract over a curried function.
I've can abstract over an uncurried function via:
def liftAU[F, P <: Product, L <: HList, R, A[_]](f: F)
(implicit
fp: FnToProduct.Aux[F, L => R],
gen: Generic.Aux[P, L],
ap: Applicative[A]
): A[P] => A[R] = p => p.map(gen.to).map(f.toProduct)
This will take a function like (Int, Int) => Int and turn it into something like Option[(Int, Int)] => Option[Int]. And it works for any arity of function.
I want to create the curried version which will take a function like Int => Int => Int and convert it to Option[Int] => Option[Int] => Option[Int].
It should also work for any arity of curried function.
Since FnToProduct only works on the first parameter list, it's not helpful here, I've also tried to write some recursive definitions at the typelevel, but I'm having issues defining the types.
Not really sure if its possible, but would love to know if others have tried anything like this.
Dmytro's answer doesn't actually work for me unless I change the instance names in one of the objects, and even then it doesn't work for a function like Int => Int => Int => Int, and I find working with Poly values really annoying, so instead of debugging the previous answer, I'm just going to write my own.
You can actually write this operation pretty nicely using a 100% Shapeless-free type class:
import cats.Applicative
trait LiftCurried[F[_], I, O] {
type Out
def apply(f: F[I => O]): F[I] => Out
}
object LiftCurried extends LowPriorityLiftCurried {
implicit def liftCurried1[F[_]: Applicative, I, I2, O2](implicit
lc: LiftCurried[F, I2, O2]
): Aux[F, I, I2 => O2, F[I2] => lc.Out] = new LiftCurried[F, I, I2 => O2] {
type Out = F[I2] => lc.Out
def apply(f: F[I => I2 => O2]): F[I] => F[I2] => lc.Out =
(Applicative[F].ap(f) _).andThen(lc(_))
}
}
trait LowPriorityLiftCurried {
type Aux[F[_], I, O, Out0] = LiftCurried[F, I, O] { type Out = Out0 }
implicit def liftCurried0[F[_]: Applicative, I, O]: Aux[F, I, O, F[O]] =
new LiftCurried[F, I, O] {
type Out = F[O]
def apply(f: F[I => O]): F[I] => F[O] = Applicative[F].ap(f) _
}
}
It's probably possible to make that a little cleaner but I find it reasonable readable as it is.
You might want to have something concrete like this:
def liftCurriedIntoOption[I, O](f: I => O)(implicit
lc: LiftCurried[Option, I, O]
): Option[I] => lc.Out = lc(Some(f))
And then we can demonstrate that it works with some functions like this:
val f: Int => Int => Int = x => y => x + y
val g: Int => Int => Int => Int = x => y => z => x + y * z
val h: Int => Int => Int => String => String = x => y => z => _ * (x + y * z)
And then:
scala> import cats.instances.option._
import cats.instances.option._
scala> val ff = liftCurriedIntoOption(f)
ff: Option[Int] => (Option[Int] => Option[Int]) = scala.Function1$$Lambda$1744/350671260#73d06630
scala> val gg = liftCurriedIntoOption(g)
gg: Option[Int] => (Option[Int] => (Option[Int] => Option[Int])) = scala.Function1$$Lambda$1744/350671260#2bb9b82c
scala> val hh = liftCurriedIntoOption(h)
hh: Option[Int] => (Option[Int] => (Option[Int] => (Option[String] => Option[String]))) = scala.Function1$$Lambda$1744/350671260#45eec9c6
We can also apply it a couple more times just for the hell of it:
scala> val hhhh = liftCurriedIntoOption(liftCurriedIntoOption(hh))
hhh: Option[Option[Option[Int]]] => (Option[Option[Option[Int]]] => (Option[Option[Option[Int]]] => (Option[Option[Option[String]]] => Option[Option[Option[String]]]))) = scala.Function1$$Lambda$1744/350671260#592593bd
So the types look okay, and for the values…
scala> ff(Some(1))(Some(2))
res0: Option[Int] = Some(3)
scala> ff(Some(1))(None)
res1: Option[Int] = None
scala> hh(Some(1))(None)(None)(None)
res2: Option[String] = None
scala> hh(Some(1))(Some(2))(Some(3))(Some("a"))
res3: Option[String] = Some(aaaaaaa)
…which I think is what you were aiming for.
You can define recursive Poly
object constNone extends Poly1 {
implicit def zeroCase[In]: Case.Aux[In, Option[Int]] = at(_ => None)
implicit def succCase[In, In1, Out](implicit
cse: Case.Aux[In, Out]): Case.Aux[In1, In => Out] = at(_ => cse(_))
}
object transform extends Poly1 {
implicit def zeroCase: Case.Aux[Int, Option[Int]] = at(Some(_))
implicit def succCase[In, Out](implicit
cse: Case.Aux[In, Out],
noneCase: constNone.Case.Aux[In, Out]
): Case.Aux[Int => In, Option[Int] => Out] =
at(f => {
case Some(n) => cse(f(n))
case None => noneCase(f(0))
})
}
(transform((x: Int) => (y: Int) => x + y) _)(Some(1))(Some(2)) //Some(3)
(transform((x: Int) => (y: Int) => x + y) _)(Some(1))(None) //None
(transform((x: Int) => (y: Int) => x + y) _)(None)(Some(2)) //None

Implicit conversion is not applied if a method has type parameter

The question is based on the discussion here. This is the setup:
implicit def CToC2(obj: C1): C2 = {
new C2()
}
class C1() {
def f[U](f: (Int, Int) => U): U = f(1, 1)
}
class C2() {
def f[U](f: ((Int, Int)) => U): U = f(2, 2)
}
I'd expect that trying to call the function with a signature that exists in C2, scala would use the implicit conversion to satisfy the call:
val c1 = new C1()
val ff: ((Int, Int)) => Unit = t => println(t._1 + t._2)
But this fails:
scala> c1.f(ff)
Error:(16, 7) type mismatch;
found : ((Int, Int)) => Unit
required: (Int, Int) => ?
Interestingly if I drop the type parameter from C1, it works fine:
class C1() {
def f(f: (Int, Int) => Unit): Unit = f(1, 1)
}

How to compose tupled unary functions by combining their input tuples

I've been playing around with shapeless for a bit now.
But, yesterday I got stuck when trying to compose tupled functions.
What I was looking into specifically is composing two unary functions f1: T => R and f2: R => U => S into f: TU => S where T is a TupleN and TU := (t1, ... , tn, u)
import shapeless.ops.tuple._
implicit class Composable[T <: Product, R](val f1: T => R) extends AnyVal{
def compose2[U, S](f2: R => U => S)(implicit p: Prepend[T, Tuple1[U]]): (p.Out => S) = {
// how to provide the two required implicits for Last[p.Out] and Init[p.Out]?
tu => f1.andThen(f2)(tu.init)(tu.last)
}
}
val f1: ((Int, Int)) => Int = x => x._1 * x._2
val f2: ((Int, Int, Int)) => Int = f1.compose2((y: Int) => (x3: Int) => x3 + y).apply _
What I've been struggling with is providing the implicit proof for the tuple operations last and init, so the above code won't compile!
From a logical perspective it feels trivial as result of Prepend, but I couldn't figure out a way. So any idea is welcome :)
Using shapeless's facilities to abstract over arity I got somehow closer:
import shapeless.ops.function.{FnFromProduct, FnToProduct}
import shapeless.{::, HList}
implicit class Composable[F](val f: F) extends AnyVal{
// the new param U is appended upfront
def compose2[I <: HList, R, U, S](f2: R => U => S)
(implicit ftp: FnToProduct.Aux[F, I => R], ffp: FnFromProduct[U :: I => S]): ffp.Out = {
ffp(list => f2.compose(ftp(f))(list.tail)(list.head))
}
}
val f1: (Int, Int) => Int = (x1,x2) => x1 * x2
val f2: (Int, Int, Int) => Int = f1.compose2((y: Int) => (x3: Int) => x3 + y).apply _
This works, but then again I was really looking for compose2 to work on unary tupled Function1s. Also, this results in f: (U, t1, ..., tn) => S rather than f: TU => S with TU := (t1, ... , tn, u).
As Miles says, this would be more convenient with an undo for Prepend, but since the length of the second part is fixed, an approach similar to the one in my other answer isn't too bad at all:
import shapeless.ops.tuple._
implicit class Composable[T <: Product, R](val f1: T => R) extends AnyVal {
def compose2[U, S, TU](f2: R => U => S)(implicit
p: Prepend.Aux[T, Tuple1[U], TU],
i: Init.Aux[TU, T],
l: Last.Aux[TU, U]
): (p.Out => S) =
tu => f1.andThen(f2)(i(tu))(l(tu))
}
And then:
scala> val f1: ((Int, Int)) => Int = x => x._1 * x._2
f1: ((Int, Int)) => Int = <function1>
scala> val f2: ((Int, Int, Int)) => Int =
| f1.compose2((y: Int) => (x3: Int) => x3 + y).apply _
f2: ((Int, Int, Int)) => Int = <function1>
scala> f2((2, 3, 4))
res1: Int = 10
The trick is adding the output of Prepend to the type parameter list for compose2—which will generally be inferred—and then using Prepend.Aux to make sure that it's inferred appropriately. You'll often find in Shapeless that you need to refer to the output type of a type class in other type class instances in the same implicit parameter list in this way, and the Aux type members make doing so a little more convenient.