Skip to content

Instantly share code, notes, and snippets.

@folone
Created November 29, 2011 10:28
Show Gist options
  • Save folone/1404336 to your computer and use it in GitHub Desktop.
Save folone/1404336 to your computer and use it in GitHub Desktop.
Scalaz partial modification of immutable objects
scala> import scalaz._
import scalaz._
scala> case class Person(name: String, age: Int)
defined class Person
scala> val nameLens: Lens[Person, String] =
| Lens((p: Person) => p.name,
| (p: Person, changed: String) => p.copy(name = changed))
nameLens: scalaz.Lens[Person,String] = Lens(<function1>,<function2>)
scala> val ageLens: Lens[Person, Int] =
| Lens((p: Person) => p.age,
| (p: Person, changed: Int) => p.copy(age = changed))
ageLens: scalaz.Lens[Person,Int] = Lens(<function1>,<function2>)
scala> val p = Person("George", 24)
p: Person = Person(George,24)
scala> val p2 = ageLens.set(p, 25)
p2: Person = Person(George,25)
scala> nameLens.set(p2, "OtherName")
res2: Person = Person(OtherName,25)
scala> import Scalaz._
import Scalaz._
scala> val z = zipper(Stream(9, 11), 7, Stream(23, 9))
z: scalaz.Zipper[Int] = <zipper>
scala> z.shows
res3: String = [11,9] 7 [23,9]
scala> val znext = z.tryNext
znext: scalaz.Zipper[Int] = <zipper>
scala> znext.shows
res4: String = [11,9,7] 23 [9]
scala> val zinsertl = znext.insertLeft(11)
zinsertl: scalaz.Zipper[Int] = <zipper>
scala> zinsertl.shows
res6: String = [11,9,7] 11 [23,9]
scala> val zinsertr = znext.insertRight(89)
zinsertr: scalaz.Zipper[Int] = <zipper>
scala> zinsertr.shows
res7: String = [11,9,7,23] 89 [9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment