Skip to content

Instantly share code, notes, and snippets.

@felher
Created January 27, 2020 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felher/cdeaf5ea091ba74ff11c2515d5e13ac5 to your computer and use it in GitHub Desktop.
Save felher/cdeaf5ea091ba74ff11c2515d5e13ac5 to your computer and use it in GitHub Desktop.
package org.felher.tmpc5C0ubzOfr
import shapeless._, syntax.singleton._, record._, shapeless.ops.record._
object Main {
def main(args: Array[String]): Unit = {
val a = ('name ->> "Alice") :: ('birthYear ->> 1980) :: HNil
val b = ('name ->> "Bob") :: ('birthYear ->> 1990) :: HNil
val ageAnnotater = makeAgeAnnotator(2020)
println(
List(a, b)
.map(i => ageAnnotater.apply(i))
.map(i => nameLenghtAnnotater.apply(i))
);
}
def makeAgeAnnotator(nowYear: Int) = new Stage {
type Required = Record.`'birthYear -> Int`.T
type Out = Record.`'age -> Int`.T
def execute(r: Required): Out = {
val age = nowYear - r('birthYear)
('age ->> age) :: HNil
}
}
val nameLenghtAnnotater = new Stage {
type Required = Record.`'name -> String`.T
type Out = Record.`'nameLength -> Int`.T
def execute(r: Required): Out =
('nameLength ->> r('name).length) :: HNil
}
}
abstract class Stage {
type Required <: HList
type Out <: HList
def execute(r: Required): Out
def apply[In <: HList](in: In)(implicit
e: Extractor[In, Required],
m: Merger[In, Out]
): m.Out = {
val tmp = in.extract[Required]
val added = execute(tmp)
in.merge(added)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment