Type safe type combinations with shapeless - scala

Having the following code:
import shapeless.{::, Generic, HList, HNil, Lazy}
object Problem {
trait In {
def bar: Double
}
trait A {
def foo: Int
type I <: In
}
/////////////////////////////////////////////////////
final case class A1In(d: Double) extends In {
override def bar: Double = 1.1 + d
}
final case class A1() extends A {
override def foo: Int = 1
override type I = A1In
}
final case class A2In(d: Double) extends In {
override def bar: Double = 1.1 + d
}
final case class A2() extends A {
override def foo: Int = 1
override type I = A2In
}
final case class AListIn[T <: HList](items: T)(implicit ev: isIn[T]) extends In {
override def bar = 1.1
}
final case class AList[T <: HList](items: T)(implicit ev: isA[T]) extends A {
override def foo: Int = 555
override type I = AListIn[???]
}
trait isA[T] {
def aux_foo(value: T): Int
}
trait isIn[T] {
def aux_bar(value: T): Double
}
/////////////////////////////////////////////////////
def alloc(a: A): In = ????
def usage() = {
val a1: A1 = A1()
val a2: A2 = A2()
val l: AList[::[A1, ::[A2, ::[A1, HNil]]]] = AList(a1 :: a2 :: a1 :: HNil)
val a1In: A1In = A1In(1.2)
val a2In: A2In = A2In(9.3)
val lIn: AListIn[::[A2In, ::[A1In, HNil]]] = AListIn(a2In :: a1In :: HNil)
}
}
How can I fix it so it works as expected?
E.g how do I get correct type in place of ??? which is a proper type HList being result of applying isA -> isIn type mapping. The mapping must follow the natural association of A -> In mapping defined as type I <: In in trait A
And how to implement alloc function which for any concrete instance of In will produce corresponding instance of A?
Should concrete implementations of In be path dependent types of corresponding As?
Below is the code for isA the code for isIn is analogous
trait isA[T] {
def aux_foo(value: T): Int
}
object isA {
// "Summoner" method
def apply[T](implicit enc: isA[T]): isA[T] = enc
// "Constructor" method
def instance[T](func: T => Int): isA[T] = new isA[T] {
override def aux_foo(value: T): Int = func(value)
}
implicit def a1Encoder: isA[A1] = instance(i => 4)
implicit def a2Encoder: isA[A2] = instance(i => 9)
implicit def hnilEncoder: isA[HNil] = instance(hnil => 0)
implicit def hlistEncoder[H, T <: HList](implicit
hInstance: Lazy[isA[H]],
tInstance: isA[T]
): isA[H :: T] = instance {
case h :: t => hInstance.value.aux_foo(h) + tInstance.aux_foo(t)
}
implicit def genericInstance[A, R](implicit
generic: Generic.Aux[A, R],
rInstance: Lazy[isA[R]]
): isA[A] = instance { value => rInstance.value.aux_foo(generic.to(value)) }
}

Related

How to make a typeclass works with an heterogenous List in scala

Given the following typeclass and some instances for common types
trait Encoder[A] {
def encode(a: A): String
}
object Encoder {
implicit val stringEncoder = new Encoder[String] {
override def encode(a: String): String = a
}
implicit val intEncoder = new Encoder[Int] {
override def encode(a: Int): String = String.valueOf(a)
}
implicit def listEncoder[A: Encoder] =
new Encoder[List[A]] {
override def encode(a: List[A]): String = {
val encoder = implicitly[Encoder[A]]
a.map(encoder.encode).mkString(",")
}
}
}
Is there a way to make it work
Encoder.listEncoder.encode(List("a", 1))
If you define an instance for Any
object Encoder {
implicit val anyEncoder = new Encoder[Any] {
override def encode(a: Any): String = a.toString
}
//instances for String, Int, List[A]
}
then
Encoder.listEncoder[Any].encode(List("a", 1))
will work.
You have to specify type parameter here explicitly (listEncoder[Any]) because that's how type inference work in scala. Indeed, after the type of argument of encode is inferred
Encoder.listEncoder[???].encode(List("a", 1))
// ^^^^^^^^^^^^
// List[Any]
it's too late to come back to infer the type parameter of listEncoder.
If you define a delegator function
def encode[A](a: A)(implicit encoder: Encoder[A]): String = encoder.encode(a)
or syntax
implicit class EncoderOps[A](a: A)(implicit encoder: Encoder[A]) {
def encode: String = encoder.encode(a)
}
// or
// implicit class EncoderOps[A](a: A) {
// def encode(implicit encoder: Encoder[A]): String = encoder.encode(a)
// }
then you don't have to specify type parameter explicitly
encode("a")
encode(1)
encode(List("a", 1))
"a".encode
1.encode
List("a", 1).encode
By the way, List("a", 1) is not a heterogenous list, it's an ordinary homogenous list with element type Any. A heterogenous list would be
val l: String :: Int :: HNil = "a" :: 1 :: HNil
You can try a magnet instead of type class
trait Magnet {
def encode(): String
}
object Magnet {
implicit def fromInt(a: Int): Magnet = new Magnet {
override def encode(): String = String.valueOf(a)
}
implicit def fromString(a: String): Magnet = new Magnet {
override def encode(): String = a
}
}
def encode(m: Magnet): String = m.encode()
encode("a")
encode(1)
List[Magnet]("a", 1).map(_.encode())
or HList instead of List[A]
sealed trait HList
case class ::[+H, +T <: HList](head: H, tail: T) extends HList
case object HNil extends HList
type HNil = HNil.type
implicit class HListOps[L <: HList](l: L) {
def ::[A](a: A): A :: L = new ::(a, l)
}
trait Encoder[A] {
def encode(a: A): String
}
object Encoder {
implicit val stringEncoder: Encoder[String] = new Encoder[String] {
override def encode(a: String): String = a
}
implicit val intEncoder: Encoder[Int] = new Encoder[Int] {
override def encode(a: Int): String = String.valueOf(a)
}
implicit val hnilEncoder: Encoder[HNil] = new Encoder[HNil] {
override def encode(a: HNil): String = ""
}
implicit def hconsEncoder[H, T <: HList](implicit
hEncoder: Encoder[H],
tEncoder: Encoder[T]
): Encoder[H :: T] = new Encoder[H :: T] {
override def encode(a: H :: T): String =
s"${hEncoder.encode(a.head)},${tEncoder.encode(a.tail)}"
}
}
def encode[A](a: A)(implicit encoder: Encoder[A]): String = encoder.encode(a)
implicit class EncoderOps[A](a: A)(implicit encoder: Encoder[A]) {
def encode: String = encoder.encode(a)
}
val l: String :: Int :: HNil = "a" :: 1 :: HNil
encode(l)
l.encode

How to reduce constrained HList

How to fix the code below so it works?
object Foo {
object sum extends Poly {
implicit def caseFoo = use((f1: Int, f2: Int) => f1 + f2)
}
def foo[L <: HList : <<:[Int]#λ](l: L): Int = {
l.reduceLeft(sum)
// Error: could not find implicit value for parameter reducer: shapeless.ops.hlist.LeftReducer[L,com.struct.Foo.sum.type]
// l.reduceLeft(sum)
// Error: not enough arguments for method reduceLeft: (implicit reducer: shapeless.ops.hlist.LeftReducer[L,com.struct.Foo.sum.type])reducer.Out.
// Unspecified value parameter reducer.
}
}
Additionally. How to change it so it reduces HList of any Numerics?
Update:
Please consider fuller example of my problem:
import shapeless._
trait Bar {
def foo: Int
}
case class Foo[L <: HList](l: L) extends Bar {
object sum extends Poly {
implicit def caseFoo[A: Numeric] = use((f1: A, f2: A) => f1 + f2)
//Error: type mismatch;
//found : A
//required: String
}
override def foo(implicit reducer: LeftReducer[L, sum.type]): Int = reducer(l)
//Error: type mismatch;
//found : reducer.Out
//required: Int
}
Update:
package com.test
import shapeless.ops.hlist.LeftReducer
import shapeless.{HList, HNil, Poly}
trait Bar {
def foo: Int
}
case class Foo[L <: HList](list: L) extends Bar {
import Numeric.Implicits._
object sum extends Poly {
implicit def caseFoo[A: Numeric] = use((f1: A, f2: A) => f1 + f2)
}
class MkFoo[T] {
def apply(l: L)(implicit reducer: LeftReducer.Aux[L, sum.type, T]): T = reducer(l)
}
override def foo: Int = (new MkFoo[Int]())(list)
// Error: could not find implicit value for parameter reducer: shapeless.ops.hlist.LeftReducer.Aux[L,Foo.this.sum.type,Int]
}
object Testing {
def main(args: Array[String]): Unit = {
val b:Bar = Foo(1 :: 2 :: 3 :: HNil)
println(b.foo)
}
}
The LUBConstraint.<<: type is unconstructive in sense that it could only be evident that all HList members have some type, but can not derive anything from it.
To use reduceLeft method you need specifically LeftReducer operation provider. You can require it in your method directly.
import shapeless._, ops.hlist._
object Foo {
import Numeric.Implicits._
object sum extends Poly {
implicit def caseFoo[A: Numeric] = use((f1: A, f2: A) => f1 + f2)
}
def foo[L <: HList](l: L)(implicit reducer: LeftReducer[L, sum.type]): reducer.Out =
reducer(l)
}
Foo.foo(1 :: 2 :: 3 :: HNil) // res0: Int = 6
Foo.foo(1.0 :: 2.0 :: 3.0 :: HNil) // res1: Double = 6.0
Update
If you need direct evidence, that your result will be of some result type you can use additional type argument, but that needs separation of type parameters via the Typed Maker pattern
object Foo {
import Numeric.Implicits._
object sum extends Poly {
implicit def caseFoo[A: Numeric] = use((f1: A, f2: A) => f1 + f2)
}
def foo[T] = new MkFoo[T]
class MkFoo[T] {
def apply[L <: HList](l: L)(implicit reducer: LeftReducer.Aux[L, sum.type, T]): T = reducer(l)
}
}
now
Foo.foo[Int](1 :: 2 :: 3 :: HNil)
Foo.foo[Double](1.0 :: 2.0 :: 3.0 :: HNil)
will still produce correct result, while
Foo.foo[Double](1 :: 2 :: 3 :: HNil)
will fail at compile time
This works:
package com.test
import shapeless.{::, Generic, HList, HNil, Lazy}
trait Bar {
def foo: Int
}
case class Foo[L <: HList](list: L)(implicit ev: SizeCalculator[L]) extends Bar {
override def foo: Int = ev.size(list)
}
object Testing {
def main(args: Array[String]): Unit = {
val b: Bar = Foo(1 :: 2 :: 3 :: HNil)
println(b.foo)
}
}
sealed trait SizeCalculator[T] {
def size(value: T): Int
}
object SizeCalculator {
// "Summoner" method
def apply[A](implicit enc: SizeCalculator[A]): SizeCalculator[A] = enc
// "Constructor" method
def instance[A](func: A => Int): SizeCalculator[A] = new SizeCalculator[A] {
def size(value: A): Int = func(value)
}
import Numeric.Implicits._
implicit def numericEncoder[A: Numeric]: SizeCalculator[A] = new SizeCalculator[A] {
override def size(value: A): Int = value.toInt()
}
implicit def hnilEncoder: SizeCalculator[HNil] = instance(hnil => 0)
implicit def hlistEncoder[H, T <: HList](
implicit
hInstance: Lazy[SizeCalculator[H]],
tInstance: SizeCalculator[T]
): SizeCalculator[H :: T] = instance {
case h :: t =>
hInstance.value.size(h) + tInstance.size(t)
}
implicit def genericInstance[A, R](
implicit
generic: Generic.Aux[A, R],
rInstance: Lazy[SizeCalculator[R]]
): SizeCalculator[A] = instance { value => rInstance.value.size(generic.to(value)) }
def computeSize[A](value: A)(implicit enc: SizeCalculator[A]): Int = enc.size(value)
}

Scala types and inheritance

I've got an interface,
trait Heap[E, H <: Heap[E, H]] {
implicit def ord: Ordering[E]
def empty: H
def isEmpty: Boolean
def insert(x: E): H
def merge(b: H): H
def findMin: E
def deleteMin: H
def toList: List[E] =
if (isEmpty) Nil else findMin :: deleteMin.toList
}
It's generic, as we need H to define "a Heap of the same type," as def merge(b: H): H is normally defined in terms of merging heaps of the same internal structure.
That works reasonably well for the "normal" heaps, i.e. heaps that manage their internal structures themselves:
class LazyPairingHeap[E](val h: Repr[E] = Empty)
(implicit val ord: Ordering[E])
extends Heap[E, LazyPairingHeap[E]] {
import okasaki.heaps.LazyPairingHeap._
override def empty = new LazyPairingHeap[E](Empty)
override def isEmpty: Boolean = h == Empty
// etc.
and even for some of the heaps build on top of other heaps:
class SizedHeap[E, H <: Heap[E, H]](val s: Int, val h: H)
extends Heap[E, SizedHeap[E, H]] {
override implicit def ord: Ordering[E] = h.ord
override def empty = new SizedHeap[E, H](0, h.empty)
override def isEmpty = s == 0
override def insert(e: E) = new SizedHeap[E, H](s + 1, h.insert(e))
override def merge(o: SizedHeap[E, H]) = new SizedHeap[E, H](s + o.s, h.merge(o.h))
override def findMin: E = h.findMin
override def deleteMin = new SizedHeap[E, H](s - 1, h.deleteMin)
}
The problem appears when instead of merely wrapping the original heap we need to weave it into our representation:
object BootstrappedHeap {
sealed trait BSHeap[+A, +H[_]]
object Empty extends BSHeap[Nothing, Nothing] {
override def toString = "Empty"
}
case class H[A, BH[_]](x: A, bsh: BH[BSHeap[A, BH]]) extends BSHeap[A, BH] {
override def toString = s"H($x, $bsh)"
}
}
abstract class BootstrappedHeap[E,
BaseHeap[X] <: Heap[X, BaseHeap[X]],
This <: BootstrappedHeap[E, BaseHeap, This]]
(val h: BSHeap[E, BaseHeap] = Empty)
(implicit ord: Ordering[E])
extends Heap[E, This] {
implicit val hord: Ordering[BSHeap[E, BaseHeap]] =
Ordering.by {
case Empty => None
case H(x, _) => Some(x)
}
def baseHeap: BaseHeap[BSHeap[E, BaseHeap]]
def create(h: BSHeap[E, BaseHeap]): This
override def empty = create(Empty)
override def isEmpty: Boolean = h == Empty
override def insert(x: E) = create(merge(H(x, baseHeap.empty), h))
override def merge(o: This) = create(merge(h, o.h))
private def merge(a: BSHeap[E, BaseHeap], b: BSHeap[E, BaseHeap]): BSHeap[E, BaseHeap] = (a, b) match {
case (Empty, _) => b
case (_, Empty) => a
case (h1#H(x, p1), h2#H(y, p2)) =>
if (ord.lteq(x, y)) H(x, p1.insert(h2))
else H(y, p2.insert(h1))
}
// etc
Now the question is, is there a better way than this lovely type annotation?
[E,
BaseHeap[X] <: Heap[X, BaseHeap[X]],
This <: BootstrappedHeap[E, BaseHeap, This]]
X seems to be unnecessary though I found no way to get rid of it;
a reference to This seems to be a bit over the edge;
finally, BaseHeap has really nothing to do in the public interface: I want it to be an implementation detail, can I hide it?

Compiler can't find instance of derived typeclass when result is assigned to val

I have following question: having typeclass for ADT derived with LabelledTypeClassCompanion (where both product and coproduct are correctly defined) inside Scala object, why compiler can't find instance for datatype itself (coproduct), but is able to do so for parameters of specific data constructors (product) when called inside the same object and assigned to val?
Below is a snippet for Show typeclass which is mostly borrowed from corresponding Shapeless example:
import shapeless._
object ShowGeneric {
trait Show[T] {
def show(t: T): String
}
object Show extends LabelledTypeClassCompanion[Show] {
implicit def intShow: Show[Int] = new Show[Int] {
override def show(i: Int): String = i.toString
}
implicit def booleanShow: Show[Boolean] = new Show[Boolean] {
override def show(b: Boolean): String = b.toString
}
implicit def listShow[A](implicit showA: Show[A]): Show[List[A]] = new Show[List[A]] {
override def show(l: List[A]): String = l.map(showA.show).mkString("List(", ", ", ")")
}
object typeClass extends LabelledTypeClass[Show] {
override def emptyProduct: Show[HNil] = new Show[HNil] {
override def show(t: HNil): String = ""
}
override def product[H, T <: HList](name: String, sh: Show[H], st: Show[T]): Show[H :: T] = new Show[H :: T] {
override def show(t: H :: T): String = {
val head = s"$name = ${sh.show(t.head)}"
val tail = st.show(t.tail)
if(tail.isEmpty) head else s"$head, $tail"
}
}
override def coproduct[L, R <: Coproduct](name: String, cl: => Show[L], cr: => Show[R]): Show[L :+: R] = new Show[L :+: R] {
override def show(t: L :+: R): String = t match {
case Inl(l) => s"$name(${cl.show(l)})"
case Inr(r) => cr.show(r)
}
}
override def emptyCoproduct: Show[CNil] = new Show[CNil] {
override def show(t: CNil): String = ""
}
override def project[F, G](instance: => Show[G], to: F => G, from: G => F): Show[F] = new Show[F] {
override def show(t: F): String = instance.show(to(t))
}
}
}
implicit class ShowOps[T](t: T)(implicit showT: Show[T]) {
def show: String = showT.show(t)
}
sealed trait Whatever
case class IntBool(i: Int, b: Boolean) extends Whatever
case class BoolInt(b: Boolean, i: Int) extends Whatever
case class BoolListInt(b: Boolean, l: List[Int]) extends Whatever
def showWhatever(whatever: Whatever)(implicit showWhatever: Show[Whatever]): String = {
showWhatever.show(whatever)
}
val stringBoolInt = BoolInt(false, 100).show // Compiles
val stringShowWhatever = showWhatever(BoolInt(false, 100)) // Doesn't compile: could not find implicit value for parameter showWhatever:ShowGeneric.Show[ShowGeneric.Whatever]
}
Thanks in advance for your answers!

What is the purpose of the emptyCoproduct and coproduct methods of the TypeClass trait in Shapeless

It is not fully clear to me what is the purpose of the emptyCoProduct and coproduct methods of the TypeClass trait in Shapeless.
When would one use the TypeClass trait instead of the ProductTypeClass?
What are some examples of ways those two methods would be implemented?
Suppose I've got a simple type class:
trait Weight[A] { def apply(a: A): Int }
object Weight {
def apply[A](f: A => Int) = new Weight[A] { def apply(a: A) = f(a) }
}
And some instances:
implicit val stringWeight: Weight[String] = Weight(_.size)
implicit def intWeight: Weight[Int] = Weight(identity)
And a case class:
case class Foo(i: Int, s: String)
And an ADT:
sealed trait Root
case class Bar(i: Int) extends Root
case class Baz(s: String) extends Root
I can define a ProductTypeClass instance for my type class:
import shapeless._
implicit object WeightTypeClass extends ProductTypeClass[Weight] {
def emptyProduct: Weight[HNil] = Weight(_ => 0)
def product[H, T <: HList](hw: Weight[H], tw: Weight[T]): Weight[H :: T] =
Weight { case (h :: t) => hw(h) + tw(t) }
def project[F, G](w: => Weight[G], to: F => G, from: G => F): Weight[F] =
Weight(f => w(to(f)))
}
And use it like this:
scala> object WeightHelper extends ProductTypeClassCompanion[Weight]
defined object WeightHelper
scala> import WeightHelper.auto._
import WeightHelper.auto._
scala> implicitly[Weight[Foo]]
res0: Weight[Foo] = Weight$$anon$1#4daf1b4d
scala> implicitly[Weight[Bar]]
res1: Weight[Bar] = Weight$$anon$1#1cb152bb
scala> implicitly[Weight[Baz]]
res2: Weight[Baz] = Weight$$anon$1#74930887
But!
scala> implicitly[Weight[Root]]
<console>:21: error: could not find implicit value for parameter e: Weight[Root]
implicitly[Weight[Root]]
^
This is a problem—it makes our automated type class instance derivation pretty much useless for ADTs. Fortunately we can use TypeClass instead:
implicit object WeightTypeClass extends TypeClass[Weight] {
def emptyProduct: Weight[HNil] = Weight(_ => 0)
def product[H, T <: HList](hw: Weight[H], tw: Weight[T]): Weight[H :: T] =
Weight { case (h :: t) => hw(h) + tw(t) }
def project[F, G](w: => Weight[G], to: F => G, from: G => F): Weight[F] =
Weight(f => w(to(f)))
def emptyCoproduct: Weight[CNil] = Weight(_ => 0)
def coproduct[L, R <: Coproduct]
(lw: => Weight[L], rw: => Weight[R]): Weight[L :+: R] = Weight {
case Inl(h) => lw(h)
case Inr(t) => rw(t)
}
}
And then:
scala> object WeightHelper extends TypeClassCompanion[Weight]
defined object WeightHelper
scala> import WeightHelper.auto._
import WeightHelper.auto._
scala> implicitly[Weight[Root]]
res0: Weight[Root] = Weight$$anon$1#7bc44e19
All the other stuff above still works as well.
To sum up: Shapeless's Coproduct is a kind of abstraction over ADTs, and in general you should provide instances of TypeClass for your type classes instead of just ProductTypeClass whenever possible.
As of shapeless 2.3.2, the above example doesn't seem to compile. here's the updated one for future reference:
import shapeless._
import shapeless.test._
trait Weight[A] { def apply(a: A): Int }
object Weight {
def apply[A](f: A => Int) = new Weight[A] { def apply(a: A) = f(a) }
}
case class Foo(i: Int, s: String)
sealed trait Root
case class Bar(i: Int) extends Root
case class Baz(s: String) extends Root
object Base {
implicit val stringWeight: Weight[String] = Weight(_.size)
implicit def intWeight: Weight[Int] = Weight(identity)
}
object ProductTC {
object WeightHelper extends ProductTypeClassCompanion[Weight] {
object typeClass extends ProductTypeClass[Weight] {
def emptyProduct: Weight[HNil] = Weight(_ => 0)
def product[H, T <: HList](hw: Weight[H], tw: Weight[T]): Weight[H :: T] =
Weight { case (h :: t) => hw(h) + tw(t) }
def project[F, G](w: => Weight[G], to: F => G,from: G => F): Weight[F] =
Weight(f => w(to(f)))
}
}
import Base._
import WeightHelper._
implicitly[Weight[Foo]]
implicitly[Weight[Bar]]
implicitly[Weight[Baz]]
illTyped("implicitly[Weight[Root]]")
}
object TC {
object WeightTypeClass extends TypeClassCompanion[Weight] {
object typeClass extends TypeClass[Weight] {
def emptyProduct: Weight[HNil] = Weight(_ => 0)
def product[H, T <: HList](hw: Weight[H], tw: Weight[T]): Weight[H :: T] =
Weight { case (h :: t) => hw(h) + tw(t) }
def project[F, G](w: => Weight[G], to: F => G, from: G => F): Weight[F] =
Weight(f => w(to(f)))
def emptyCoproduct: Weight[CNil] = Weight(_ => 0)
def coproduct[L, R <: Coproduct]
(lw: => Weight[L], rw: => Weight[R]): Weight[L :+: R] = Weight {
case Inl(h) => lw(h)
case Inr(t) => rw(t)
}
}
}
import Base._
import WeightTypeClass._
implicitly[Weight[Root]]
}