Unable to map on HList
Asked Answered
B

1

7

I was trying to solve this problem with shapeless. However I am for some reason unable to map on the HList. I'll let the code speak for itself.

import shapeless._
import HList._

case class Foo(a: Option[Int], b: Option[Int])

val a = Foo(Some(3), None)

val b = Foo(Some(22), Some(1))

implicit val fooIso = HListIso(Foo.apply _, Foo.unapply _)

val mapper = new (({ type O2[+A] = (Option[A], Option[A]) })#O2 ~> Option) {
  def apply[A](x: (Option[A], Option[A])): Option[A] = x._1.orElse(x._2)
}

fooIso.fromHList(fooIso.toHList(a).zip(fooIso.toHList(b)).map(mapper))

Error message is:

<console>:55: error: could not find implicit value for parameter mapper: shapeless.Mapper[java.lang.Object with shapeless.~>[[+A](Option[A], Option[A]),Option],shapeless.::[(Option[Int], Option[Int]),shapeless.::[(Option[Int], Option[Int]),shapeless.HNil]]]
              fooIso.fromHList(fooIso.toHList(a).zip(fooIso.toHList(b)).map(mapper))
                                                                           ^

Why doesn't the mapping work?

Bertberta answered 11/7, 2012 at 22:26 Comment(0)
B
10

There's an easy fix: just define your function as an object instead of a val:

object f extends (({ type O2[+A] = (Option[A], Option[A]) })#O2 ~> Option) {
  def apply[A](x: (Option[A], Option[A])): Option[A] = x._1 orElse x._2
}

(Note that I've named the function f instead of mapper to avoid confusion with the mapper implicit argument to map.)

I'm not sure I can help with why—at some point I tried to work out the details of why val wouldn't work for this kind of thing in Shapeless, and I don't remember how far I got.

Banbury answered 11/7, 2012 at 23:10 Comment(1)
The implementation of Poly1 (and hence ~>) depends on being able to name a singleton type corresponding to the function-like entity being defined, as it's being defined. This goes through smoothly where that entity is an object and the value is instantiated simultaneously with the creation of a stable identifier; but not so smoothly where those two are separated (instantiation via an explicit new and creation of a stable identifier via the val definition).This makes some sort of sense, but I can't point to justifying text in the spec ... if anyone else can, please let me know.Roughish

© 2022 - 2024 — McMap. All rights reserved.