Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement product type in Scala with generic update function working on its parts

In Scala, I need to create a product type & that represents a compound value, e.g.:

val and: String & Int & User & ... = ???

I.e. and should have a String part and an Int part and a User parts inside. This is similar to Scala with keyword:

val and: String with Int with User with ... = ???

Having such product type I need a way to, having a function A => A, apply it to some product value and get that product back with A part altered. It implies that each type in product must be unique - that's acceptable.

One important limitation is that, when applying a function A => A to the product, I only know that the product has A somewhere inside but no information about other types it consists of. But as a caller of the function, I pass it a product with full type information and expect to get this full type back as part of function signature.

In pseudo-code:

def update[A, Rest](product: A & Rest, f: A => A): A & Rest

Using Shapeless or other esoteric stuff is okay for me. I tried using HLists but they are ordered, while something like heterogeneous set would be more appropriate here to represend A & Rest part.

UPDATE:

Here is the code that solves my use case taken from Régis Jean-Gilles answer below wit added read support, some comments, and improved type-safety:

object product {

  /** Product of `left` and `right` values. */
  case class &[L, R](left: L, right: R)

  implicit class AndPimp[L](val left: L) extends AnyVal {
    /** Make a product of `this` (as left) and `right`. */
    def &[R](right: R): L & R = new &(left, right)
  }

  /* Updater. */

  /** Product updater able to update value of type `A`. */
  trait ProductUpdater[P, A] {
    /** Update product value of type `A`.
      * @return updated product */
    def update(product: P, f: A ⇒ A): P
  }

  trait LowPriorityProductUpdater {
    /** Non-product value updater. */
    implicit def valueUpdater[A]: ProductUpdater[A, A] = new ProductUpdater[A, A] {
      override def update(product: A, f: A ⇒ A): A = f(product)
    }
  }

  object ProductUpdater extends LowPriorityProductUpdater {
    /** Left-biased product value updater. */
    implicit def leftProductUpdater[L, R, A](implicit leftUpdater: ProductUpdater[L, A]): ProductUpdater[L & R, A] =
      new ProductUpdater[L & R, A] {
        override def update(product: L & R, f: A ⇒ A): L & R =
          leftUpdater.update(product.left, f) & product.right
      }

    /** Right-biased product value updater. */
    implicit def rightProductUpdater[L, R, A](implicit rightUpdater: ProductUpdater[R, A]): ProductUpdater[L & R, A] =
      new ProductUpdater[L & R, A] {
        override def update(product: L & R, f: A ⇒ A): L & R =
          product.left & rightUpdater.update(product.right, f)
      }
  }

  /** Update product value of type `A` with function `f`.
    * Won't compile if product contains multiple `A` values.
    * @return updated product */
  def update[P, A](product: P)(f: A ⇒ A)(implicit updater: ProductUpdater[P, A]): P =
    updater.update(product, f)

  /* Reader. */

  /** Product reader able to read value of type `A`. */
  trait ProductReader[P, A] {
    /** Read product value of type `A`. */
    def read(product: P): A
  }

  trait LowPriorityProductReader {
    /** Non-product value reader. */
    implicit def valueReader[A]: ProductReader[A, A] = new ProductReader[A, A] {
      override def read(product: A): A = product
    }
  }

  object ProductReader extends LowPriorityProductReader {
    /** Left-biased product value reader. */
    implicit def leftProductReader[L, R, A](implicit leftReader: ProductReader[L, A]): ProductReader[L & R, A] =
      new ProductReader[L & R, A] {
        override def read(product: L & R): A =
          leftReader.read(product.left)
      }

    /** Right-biased product value reader. */
    implicit def rightProductReader[L, R, A](implicit rightReader: ProductReader[R, A]): ProductReader[L & R, A] =
      new ProductReader[L & R, A] {
        override def read(product: L & R): A =
          rightReader.read(product.right)
      }
  }

  /** Read product value of type `A`.
    * Won't compile if product contains multiple `A` values.
    * @return value of type `A` */
  def read[P, A](product: P)(implicit productReader: ProductReader[P, A]): A =
    productReader.read(product)

  // let's test it

  val p = 1 & 2.0 & "three"

  read[Int & Double & String, Int](p) // 1
  read[Int & Double & String, Double](p) // 2.0
  read[Int & Double & String, String](p) // three

  update[Int & Double & String, Int](p)(_ * 2) // 2 & 2.0 & three
  update[Int & Double & String, Double](p)(_ * 2) // 1 & 4.0 & three
  update[Int & Double & String, String](p)(_ * 2) // 1 & 2.0 & threethree

}
like image 900
Tvaroh Avatar asked Nov 05 '15 09:11

Tvaroh


2 Answers

Here's a solution using only pure scala with no required library. It relies on a type class using a rather standard approach:

scala> :paste
// Entering paste mode (ctrl-D to finish)
case class &[L,R](left: L, right: R)
implicit class AndOp[L](val left: L) {
  def &[R](right: R): L & R = new &(left, right)
}

trait ProductUpdater[P,A] {
  def apply(p: P, f: A => A): P
}
trait LowPriorityProductUpdater {
  implicit def noopValueUpdater[P,A]: ProductUpdater[P,A] = {
    new ProductUpdater[P,A] {
      def apply(p: P, f: A => A): P = p // keep as is
    }
  }
}
object ProductUpdater extends LowPriorityProductUpdater {
  implicit def simpleValueUpdater[A]: ProductUpdater[A,A] = {
    new ProductUpdater[A,A] {
      def apply(p: A, f: A => A): A = f(p)
    }
  }
  implicit def productUpdater[L, R, A](
    implicit leftUpdater: ProductUpdater[L, A], rightUpdater: ProductUpdater[R, A]
  ): ProductUpdater[L & R, A] = {
    new ProductUpdater[L & R, A] {
      def apply(p: L & R, f: A => A): L & R = &(leftUpdater(p.left, f), rightUpdater(p.right, f))
    }
  }
}
def update[A,P](product: P)(f: A => A)(implicit updater: ProductUpdater[P,A]): P = updater(product, f)
// Exiting paste mode, now interpreting.

Let's test it:

scala> case class User(name: String, age: Int)
defined class User

scala> val p: String & Int & User & String = "hello" & 123 & User("Elwood", 25) & "bye"
p: &[&[&[String,Int],User],String] = &(&(&(hello,123),User(Elwood,25)),bye)

scala> update(p){ i: Int => i + 1 }
res0: &[&[&[String,Int],User],String] = &(&(&(hello,124),User(Elwood,25)),bye)

scala> update(p){ s: String => s.toUpperCase }
res1: &[&[&[String,Int],User],String] = &(&(&(HELLO,123),User(Elwood,25)),BYE)

scala> update(p){ user: User =>
     |   user.copy(name = user.name.toUpperCase, age = user.age*2)
     | }
res2: &[&[&[String,Int],User],String] = &(&(&(hello,123),User(ELWOOD,50)),bye)

Update: In response to:

Is it possible to make this not compile when a product doesn't contain a value to update

Yes it is most definitely possible. We could alter the ProductUpdatertype class but in this case I find it much easier to introduce a separate type class ProductContainsType as an evidence that a given product P contains at least one element of type A:

scala> :paste
// Entering paste mode (ctrl-D to finish)

@annotation.implicitNotFound("Product ${P} does not contain type ${A}")
abstract sealed class ProductContainsType[P,A]
trait LowPriorityProductContainsType {
  implicit def compositeProductContainsTypeInRightPart[L, R, A](
    implicit rightContainsType: ProductContainsType[R, A]
  ): ProductContainsType[L & R, A] = null
}
object ProductContainsType extends LowPriorityProductContainsType {
  implicit def simpleProductContainsType[A]: ProductContainsType[A,A] = null
  implicit def compositeProductContainsTypeInLeftPart[L, R, A](
    implicit leftContainsType: ProductContainsType[L, A]
  ): ProductContainsType[L & R, A] = null
}
// Exiting paste mode, now interpreting.

Now we can define our stricter update method:

def strictUpdate[A,P](product: P)(f: A => A)(
  implicit 
    updater: ProductUpdater[P,A], 
    containsType: ProductContainsType[P,A]
): P = updater(product, f)

Let's see:

scala> strictUpdate(p){ s: String => s.toUpperCase }
res21: &[&[&[String,Int],User],String] = &(&(&(HELLO,123),User(Elwood,25)),BYE)

scala> strictUpdate(p){ s: Symbol => Symbol(s.name.toUpperCase) }
<console>:19: error: Product &[&[&[String,Int],User],String] does not contain type Symbol
              strictUpdate(p){ s: Symbol => Symbol(s.name.toUpperCase) }
like image 144
Régis Jean-Gilles Avatar answered Nov 03 '22 20:11

Régis Jean-Gilles


Not an optimal variant, seems to me @TravisBrown or @MilesSabin can provide more complete answer.

In examples we will use shapeless 2.2.5. So we can represent the necessary type as a HList (no arity problem). As it is a HList it is possible to apply a Poly function:

trait A
def aFunc(a: A) = a

trait lowPriority extends Poly1 {
  implicit def default[T] = at[T](poly.identity)
}

object polyApplyToTypeA extends lowPriority {
  implicit def caseA = at[A](aFunc(_))
}

list.map(polyApplyToTypeA) //> applies only to type A

That was the first approach, using it we should use only special Poly functions (it is possible to generate them), actually, that's a problem.

The second approach is to define an own function, which has a bit difficult logic:

def applyToType[L <: HList, P <: HList, PO <: HList, S <: HList, F]
(fun: F => F, l: L)
(implicit partition: Partition.Aux[L, F, P, S],
                 tt: ToTraversable.Aux[P, List, F],
                 ft: FromTraversable[P],
                  p: Prepend.Aux[S, P, PO],
                  a: Align[PO, L]): L = 
(l.filterNot[F] ::: l.filter[F].toList[F].map(fun).toHList[P].get).align[L]

This function filters HList by a type, converts it to a List, applies our function, and converts it back to HList, also aligns types, in order not to change HList type alignment. Works as expected. Full example here: https://gist.github.com/pomadchin/bf46e21cb180c2a81664

like image 40
DaunnC Avatar answered Nov 03 '22 18:11

DaunnC