2014-04-15 15 views
8

In object Sized (in "shapeless/sized.scala") c'è unapplySeq, che sfortunatamente non fornisce un controllo statico. Ad esempio di codice fallirà a runtime con MatchError:Missing Sized.unapply

Sized(1, 2, 3) match { case Sized(x, y) => ":(" } 

sarebbe meglio se c'era unapply metodo preferibilmente, tornando Possibilità di tupla, e la forma concreta di tupla è stato costruito in base alla dimensione dell'istanza Sized. Ad esempio:

Sized(1) => x 
Sized(1, 2) => (x, y) 
Sized(1, 2, 3) => (x, y, z) 

In tal caso codice precedente fallirebbe di compilare con constructor cannot be instantiated to expected type.

Please help me attuare unapply per object Sized. Questo metodo è già implementato ovunque?

Grazie in anticipo!

risposta

5

Questo è sicuramente possibile (almeno per Sized dove N è inferiore a 23), ma l'unico approccio che riesco a pensare (escludendo macro, ecc.) È un po 'disordinato. In primo luogo abbiamo bisogno di una classe tipo che ti ci aiutano a convertire collezioni dimensioni per HList s:

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

E poi possiamo definire un oggetto estrattore che utilizza questa conversione:

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

E poi:

scala> val SafeSized(x, y, z) = Sized(1, 2, 3) 
x: Int = 1 
y: Int = 2 
z: Int = 3 

Ma:

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

Come desiderato.

Problemi correlati