1 import scala.collection.immutable.Set 2 val set135 = Set(1,3,5) //> set135 : scala.collection.immutable.Set[Int] = Set(1, 3, 5)
3 Lens.setMembershipLens(3) get set135 //> res0: Boolean = true
4 Lens.setMembershipLens(7).set(set135,true) //> res1: Set[Int] = Set(1, 3, 5, 7)
5 Lens.setMembershipLens(5).set(set135,false) //> res2: Set[Int] = Set(1, 3)
6
7
8 import scala.collection.immutable.Map 9 val fooMap = Map(1 -> "A", 2 -> "B") //> fooMap : scala.collection.immutable.Map[Int,String] = Map(1 -> A, 2 -> B)
10 Lens.mapVLens(1) get fooMap //> res3: Option[String] = Some(A)
11 Lens.mapVLens(3).set(fooMap,"C".some) //> res4: Map[Int,String] = Map(1 -> A, 2 -> B, 3 -> C)
12 Lens.mapVLens(1).set(fooMap,None) //> res5: Map[Int,String] = Map(2 -> B)
1 case class Company(name: String, employees: Set[String], ids: Map[Int,String], breaks: Queue[String]) 2 val titleL = Lens.lensu[Company,String]((c,n) => c.copy(name = n), _.name) 3 //> titleL : scalaz.Lens[Exercises.LensDemo.Company,String] = scalaz.LensFunct 4 //| ions$$anon$5@385c9627
5 val empSetLens = Lens.lensu[Company,Set[String]]((c,e) => c.copy(employees = e), _.employees) 6 //> empSetLens : scalaz.Lens[Exercises.LensDemo.Company,scala.collection.immut 7 //| able.Set[String]] = scalaz.LensFunctions$$anon$5@139982de
8 val idMapLens = Lens.lensu[Company,Map[Int,String]]((c,i) => c.copy(ids = i), _.ids) 9 //> idMapLens : scalaz.Lens[Exercises.LensDemo.Company,scala.collection.immuta 10 //| ble.Map[Int,String]] = scalaz.LensFunctions$$anon$5@682b2fa
11 val breakQLens = Lens.lensu[Company,Queue[String]]((c,b) => c.copy(breaks = b), _.breaks) 12 //> breakQLens : scalaz.Lens[Exercises.LensDemo.Company,scala.collection.immut 13 //| able.Queue[String]] = scalaz.LensFunctions$$anon$5@217ed35e
14
15 val foos = Company("The Foos Co, Ltd.", 16 Set("peter","john","susan"), 17 Map(1 -> "peter", 2 -> "john", 3 -> "susan"), 18 Queue("breakfast","lunch","dinner")) //> foos : Exercises.LensDemo.Company = Company(The Foos Co, Ltd.,Set(peter, j 19 //| ohn, susan),Map(1 -> peter, 2 -> john, 3 -> susan),Queue(breakfast, lunch, 20 //| dinner))
21 val newCompany = for { 22 n <- titleL 23 _ <- titleL := "The New Foo Foo Company"
24 _ <- empSetLens -= "john"
25 _ <- empSetLens += "kitty"
26 _ <- idMapLens -= 2
27 _ <- idMapLens += (2 -> "kitty") 28 bf <- breakQLens.dequeue 29 lc <- breakQLens.dequeue 30 dn <- breakQLens.dequeue 31 _ <- breakQLens.enqueue(bf) 32 _ <- breakQLens.enqueue(lc) 33 _ <- breakQLens.enqueue("afternoon tea") 34 _ <- breakQLens.enqueue(dn) 35 newOne <- get
36 } yield newOne //> newCompany : scalaz.IndexedState[Exercises.LensDemo.Company,Exercises.Lens 37 //| Demo.Company,Exercises.LensDemo.Company] = scalaz.package$IndexedState$$ano 38 //| n$2@2cd76f31
39 newCompany eva l foos //> res7: scalaz.Id.Id[Exercises