缺少Sized.unapply

Dmy*_*sud 8 scala shapeless

In object Sized(在"shapeless/sized.scala"中)unapplySeq,遗憾的是不提供静态检查.例如,下面的代码在运行时将失败MatchError:

Sized(1, 2, 3) match { case Sized(x, y) => ":(" }
Run Code Online (Sandbox Code Playgroud)

如果有unapply方法而不是返回元组的选项,并且根据大小实例的大小构造元组的具体形状会更好.例如:

Sized(1) => x
Sized(1, 2) => (x, y)
Sized(1, 2, 3) => (x, y, z)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,以前的代码片段将无法编译constructor cannot be instantiated to expected type.

请帮我实现unapplyobject Sized.这种方法是否已在任何地方实施

提前致谢!

Tra*_*own 5

这绝对是可能的(至少SizedN小于23的地方),但我能想到的唯一方法(禁止宏等)有点混乱.首先,我们需要一个类型类来帮助我们将大小的集合转换为HLists:

import shapeless._, Nat._0
import scala.collection.generic.IsTraversableLike

trait SizedToHList[R, N <: Nat] extends DepFn1[Sized[R, N]] {
  type Out <: HList
}

object SizedToHList {
  type Aux[R, N <: Nat, Out0 <: HList] = SizedToHList[R, N] { type Out = Out0 }

  implicit def emptySized[R]: Aux[R, Nat._0, HNil] = new SizedToHList[R, _0] {
    type Out = HNil
    def apply(s: Sized[R, _0]) = HNil
  }

  implicit def otherSized[R, M <: Nat, T <: HList](implicit
    sth: Aux[R, M, T],
    itl: IsTraversableLike[R]
  ): Aux[R, Succ[M], itl.A :: T] = new SizedToHList[R, Succ[M]] {
    type Out = itl.A :: T
    def apply(s: Sized[R, Succ[M]]) = s.head :: sth(s.tail)
  }

  def apply[R, N <: Nat](implicit sth: SizedToHList[R, N]): Aux[R, N, sth.Out] =
    sth

  def toHList[R, N <: Nat](s: Sized[R, N])(implicit
    sth: SizedToHList[R, N]
  ): sth.Out = sth(s)
}
Run Code Online (Sandbox Code Playgroud)

然后我们可以定义一个使用此转换的提取器对象:

import ops.hlist.Tupler

object SafeSized {
  def unapply[R, N <: Nat, L <: HList, T <: Product](s: Sized[R, N])(implicit
    itl: IsTraversableLike[R],
    sth: SizedToHList.Aux[R, N, L],
    tupler: Tupler.Aux[L, T]
  ): Option[T] = Some(sth(s).tupled)
}
Run Code Online (Sandbox Code Playgroud)

然后:

scala> val SafeSized(x, y, z) = Sized(1, 2, 3)
x: Int = 1
y: Int = 2
z: Int = 3
Run Code Online (Sandbox Code Playgroud)

但:

scala> val SafeSized(x, y) = Sized(1, 2, 3)
<console>:18: error: wrong number of arguments for object SafeSized
       val SafeSized(x, y) = Sized(1, 2, 3)
                    ^
<console>:18: error: recursive value x$1 needs type
       val SafeSized(x, y) = Sized(1, 2, 3)
                     ^
Run Code Online (Sandbox Code Playgroud)

如预期的.