noodling towards a functional brain

Wednesday, April 15, 2009

A Scala Koan

I just came across this post from James Iry on the Scala list.

"It's not part of the language so you write your own and decide if it's too confusing to be useful."


class LazyVar[T](init : => T) {
private var thunk : (() => T) = {() => {thunk = {() => init}; thunk()}}

def ! = synchronized { thunk() }
def :=(newVal : => T) = synchronized { thunk = {() => {thunk = {() => newVal}; thunk()}}}

def morph(f : T => T) = synchronized { val oldThunk = thunk ; thunk = { () => { thunk = {() => f(oldThunk())}; thunk()}}}
}

object LazyVar {
def apply[T](init : => T) = new LazyVar({init})
}

scala> val x = LazyVar(1)
x: LazyVar[Int] = LazyVar@5354a

scala> x := {println("assigning 2"); 2}

scala> x := {println("assigning 3"); 3}

scala> x!
assigning 3
res16: Int = 3


It's a Scala koan!

About Me

My photo
aspiring to elegant simplicity