7

この問題を shapeless で解決しようとしていました。しかし、何らかの理由で にマッピングできませんHList。コードに語らせます。

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))

エラーメッセージは次のとおりです。

<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))
                                                                           ^

マッピングが機能しないのはなぜですか?

4

1 に答える 1

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.

于 2012-07-11T23:10:16.593 に答える