Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Created March 4, 2018 15:00
Show Gist options
  • Save yasuabe/4d542dc10aceee6aeef5959b6aa9dbef to your computer and use it in GitHub Desktop.
Save yasuabe/4d542dc10aceee6aeef5959b6aa9dbef to your computer and use it in GitHub Desktop.
import shapeless.ops.hlist.{Length, Repeat}
import shapeless.{::, Generic, HList, HNil, Nat}
case class IceCream(name: String, numCherries: Int, inCone: Boolean)
def repeat[I <: HList, L <: Nat, O <: HList](in: I, s: String)(
implicit
len: Length.Aux[I, L],
rep: Repeat.Aux[String :: HNil, L, O]
): O = rep(s :: HNil)
def extract[A](start: Int, end: Int, convert: String => A): String => A =
line => convert(line.substring(start - 1, end).trim)
val extractors =
extract(1, 12, identity) ::
extract(13, 14, _.toInt) ::
extract(15, 17, _ == "yes") ::
HNil
def lineToIceCream(line: String): IceCream =
Generic[IceCream].from(extractors zipApply repeat(extractors, line))
val lines = List (
"Sundae 1no ", // IceCream(Sundae, 1, false),
"Cornetto 13yes", // IceCream(Cornetto, 13, true),
"Banana Split 0no ") // IceCream(Banana Split, 0, false)
.map(lineToIceCream)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment