Skip to content

Commit

Permalink
#15 - Attempt to use Generic and HListNthLensAux to generate lenses
Browse files Browse the repository at this point in the history
  • Loading branch information
julien-truffaut committed Mar 10, 2014
1 parent 64310c9 commit 9a634b0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
14 changes: 12 additions & 2 deletions core/src/main/scala/monocle/thirdparty/HList.scala
@@ -1,7 +1,7 @@
package monocle.thirdparty

import monocle.Lens
import shapeless.HList
import monocle.{SimpleLens, Iso, Lens}
import shapeless._


object hlist extends HListInstances
Expand All @@ -15,4 +15,14 @@ trait HListInstances {
Lens[HL[A1, HL[A2, T]], HL[A1, HL[New, T]], A2, New](_.tail.head, (l, a) => l.copy(tail = l.tail.copy(head = a)))


def pairToHListIso[A1, A2, B1, B2] =
Iso[(A1, A2), (B1, B2), HL[A1, HL[A2, HNil]], HL[B1, HL[B2, HNil]]](t => t._1 :: t._2 :: HNil,
hl => hl.head -> hl.tail.head
)

def first[S, A, L <: HList](implicit gen : Generic.Aux[S, L], nth : HListNthLensAux[L, shapeless.nat._0.N, A]) = at(shapeless.nat._0)

def at[S, A, L <: HList](n : Nat)(implicit gen : Generic.Aux[S, L], nth : HListNthLensAux[L, n.N, A]) =
SimpleLens[S, A](s => nth.get(gen.to(s)), (s, a) => gen.from(nth.set(gen.to(s))(a)) )

}
13 changes: 12 additions & 1 deletion examples/src/main/scala/monocle/HListExample.scala
@@ -1,7 +1,7 @@
package monocle

import monocle.thirdparty.hlist._
import shapeless.HNil
import shapeless._

object HListExample extends App {

Expand All @@ -13,4 +13,15 @@ object HListExample extends App {

println( _2.get(l) ) // "bla"

println( pairToHListIso.get((1,"bla")) ) // 1
println( (pairToHListIso compose _1[Int, HL[String,HNil], Char]).set((1,"bla"), 'c') ) // ('c', "bla")


case class Person(name : String, age : Int)
val julien = Person("Julien", 27)

println( first.get(julien) )



}

0 comments on commit 9a634b0

Please sign in to comment.