Name: shapeless-utils
Owner: Hammer Lab
Description: shapeless-style type-classes for structural manipulation of algebraic data types
Created: 2017-10-14 02:02:39.0
Updated: 2017-10-19 02:51:30.0
Pushed: 2018-01-15 00:25:35.0
Homepage: null
Size: 35
Language: Scala
GitHub Committers
User | Most Recent Commit | # Commits |
---|
Other Committers
User | Most Recent Commit | # Commits |
---|
shapeless-style type-classes for structural manipulation of algebraic data types
Find
: recursively find fields by type and/or namehlist.Find
: recursively find field by typerecord.Find
: recursively find field by namerecord.Field
: recursively find field by name and typeFlatten
: recursively flatten an HList
or case class
into an HList
Select
: covariant version of shapeless.ops.hlists.Selector
Cast
: evidence that a product ? or all branches of a coproduct ? matches a given HList structureSingleton
: above when the HList contains one elementSetup, from test//Utils.scala:
class A(n: Int)
class B(s: String)
class C(a: A, b: B)
class D(b: Boolean)
class E(c: C, d: D, a: A, a2: A)
class F(e: E)
a = A(123)
b = B("abc")
c = C(a, b)
d = D(true)
e = E(c, d, A(456), A(789))
f = F(e)
Import syntax:
rt hammerlab.shapeless._
findt
Find field by type
ndt[Int] // 123
ndt[String] // "abc"
ndt[Int] // 123
ndt[String] // "abc"
ndt[Boolean] // true
ndt[B] // b
ndt[C] // c
ndt[D] // d
ndt[Boolean] // true
ndt[String] // "abc"
ndt[A] // doesn't compile: E.a, E.a2, and E.c.a both match
ndt[Int] // doesn't compile: E.a.n, E.a2.n, and E.c.a.n both match
(adapted from hlist.FindTest)
find
Find field by name:
nd('n) // 123
nd('s) // "abc"
nd('n) // 123
nd('s) // "abc"
nd('b) // true
nd('b) // B("abc")
nd('c) // C(A(123), B("abc"))
nd('d) // D(true)
nd('s) // "abc"
nd('a2) // A(789)
nd('a) // doesn't compile: E.c.a and E.a both match
nd('n) // doesn't compile: E.a.n, E.a2.n, and E.c.a.n both match
(adapted from record.FindTest)
field
Find field by name and type:
eld[Boolean]('b) // true
eld[B]('b) // B("abc")
Singleton
/ .map
Manipulate a generic hierarchy that always wraps one element of a given type.
Example hierarchy:
ed trait Foo
class A(n: Int) extends Foo
ed trait Bar extends Foo
class B(n: Int) extends Bar
class C(n: Int) extends Bar
class D(n: Int) extends Bar
Transform the enclosed Int
, preserving concrete type:
icit val singleton = Singleton[Foo, Int]
foos = Seq[Foo](A(1), B(2), C(3), D(4))
.map(_.map(_ * 10))
eq(A(10), B(20), C(30), D(40))
Cast
Generalization of the above, providing evidence that a type is structured like a given HList
.
Given a hierarchy with all leafs matching Int :: String :: HNil
:
ed trait X
class Y(n: Int, s: String) extends X
class Z(n: Int, s: String) extends X
y = Y(111, "abc")
z = Z(222, "def")
xs = Seq[X](y, z)
Expose a map
operation that transforms the HList representation, preserving the container type:
rt shapeless._
ap {
map {
case n :: s :: ? ?
2*n :: s.reverse :: ?
eq(Y(222, cba), Z(444, fed))