Created
August 23, 2011 11:19
-
-
Save milessabin/1164885 to your computer and use it in GitHub Desktop.
Boxed lazy values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Is this even faintly novel? The closest I've seen is | |
// | |
// http://stackoverflow.com/questions/2618891/using-lazy-evaluation-functions-in-varargs | |
// | |
// which is a bit clunky by comparison. But this is so trivial someone must have | |
// done it this way before. | |
// UPDATE: | |
// Thanks to the Twittersphere (@etorreborre, @pchiusano and @loverdos) for a few sightings of related things, | |
// | |
// https://github.com/etorreborre/specs2/blob/1.5/src/main/scala/org/specs2/control/LazyParameter.scala | |
// https://github.com/scalaz/scalaz/blob/master/core/src/main/scala/scalaz/Name.scala (Need at the bottom) | |
// http://blog.ckkloverdos.com/2008/07/24/implementing-lazy-values-in-scala-at-the-language-level/ | |
object Lazy extends App { | |
class Lazy[T](t0 : => T) { | |
private lazy val t = t0 | |
def force : T = t | |
} | |
implicit def mkLazy[T](t : => T) = new Lazy(t) | |
implicit def mkEager[T](l : Lazy[T]) : T = l.force | |
def obs[T](t : T) = { println("Observing: "+t) ; t } | |
def lazySeq[T](ts : Lazy[T]*) = ts | |
val ls = lazySeq(obs(1), obs(2), obs(3)) | |
println("Head:") | |
val e1 = ls.head+1 | |
println(e1) | |
println("Map:") | |
val s = ls.map(_ + 1) | |
println(s) | |
} |
https://github.com/scalaz/scalaz/blob/scalaz-seven/core/src/main/scala/scalaz/Name.scala#L33
(Latest and greatest and least buggiest)
And of course, it's a Monad :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This kind of Lazy type is very useful, because by-name parameter is not a first-class type.