Last active
August 29, 2015 13:57
-
-
Save psttf/9763127 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import shapeless._; import syntax.singleton._; import record._ | |
object os { | |
trait OptionSelector[L <: HList, K] { | |
type Out | |
def apply(l : L): Out | |
} | |
trait LowPriorityOptionSelector { | |
type Aux[L <: HList, K, Out0] = OptionSelector[L, K] { type Out = Out0 } | |
implicit def hnilSelect[K] = new OptionSelector[HNil, K] { | |
type Out = None.type | |
def apply(l: HNil) = None | |
} | |
implicit def hlistSelect[H, T <: HList, K] | |
(implicit st : OptionSelector[T, K]): Aux[H :: T, K, st.Out] = | |
new OptionSelector[H :: T, K] { | |
type Out = st.Out | |
def apply(l : H :: T): Out = st(l.tail) | |
} | |
} | |
object OptionSelector extends LowPriorityOptionSelector { | |
implicit def hlistSelect1[K, V, T <: HList]: Aux[FieldType[K, V] :: T, K, Some[V]] = | |
new OptionSelector[FieldType[K, V] :: T, K] { | |
type Out = Some[V] | |
def apply(l : FieldType[K, V] :: T): Out = Some(l.head) | |
} | |
} | |
} | |
import os._ | |
def getOption[L <: HList, K](l: L, k: Witness)(implicit | |
s: OptionSelector[L,k.T] | |
) = s(l) | |
val l = "a" ->> 1 :: HNil | |
val i: Option[Int] = getOption(l,"a") | |
val n: None.type = getOption(l,"b") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment