Skip to content

Instantly share code, notes, and snippets.

@milessabin
Last active December 13, 2015 20:58
Show Gist options
  • Save milessabin/4973961 to your computer and use it in GitHub Desktop.
Save milessabin/4973961 to your computer and use it in GitHub Desktop.
Lazy pattern matching in Scala made even lazier with scalaz's Need.
Welcome to Scala version 2.9.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_05).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import scalaz._
import scalaz._
scala> val (foo, bar, baz) = (Need({println("foo") ; "foo"}), Need({ println("bar") ; "bar"}), Need({ println("baz") ; "baz"}))
foo: scalaz.Need[java.lang.String] = scalaz.Need$$anon$4@1d90d034
bar: scalaz.Need[java.lang.String] = scalaz.Need$$anon$4@e551516
baz: scalaz.Need[java.lang.String] = scalaz.Need$$anon$4@73db5eb3
scala> lazy val List(a, b, c) = List(foo, bar, baz)
a: scalaz.Need[java.lang.String] = <lazy>
b: scalaz.Need[java.lang.String] = <lazy>
c: scalaz.Need[java.lang.String] = <lazy>
scala> a
res0: scalaz.Need[java.lang.String] = scalaz.Need$$anon$4@1d90d034
scala> b
res1: scalaz.Need[java.lang.String] = scalaz.Need$$anon$4@e551516
scala> c
res2: scalaz.Need[java.lang.String] = scalaz.Need$$anon$4@73db5eb3
scala> a.value
foo
res3: java.lang.String = foo
scala> b.value
bar
res4: java.lang.String = bar
scala> c.value
baz
res5: java.lang.String = baz
@clhodapp
Copy link

What does the first level of laziness (lazy vals) gain you that using Need doesn't?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment