Created
January 23, 2018 08:41
-
-
Save tldeti/93d55ddce8a786af276492ffa8fa9aab to your computer and use it in GitHub Desktop.
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
sealed trait Ref[T]{ | |
def get:T | |
def registWatcher(f:()=>Unit):Unit | |
} | |
case class ElemRef[T](var v:T) extends Ref[T]{ | |
override def get: T = v | |
var callbacks:Vector[()=>Unit] =Vector() | |
def set(x:T) = { | |
v = x | |
callbacks.foreach(x=>x()) | |
} | |
def map[B](f:T=>B) = new RefF(this,f) | |
def registWatcher(f:()=>Unit) = callbacks = callbacks :+ f | |
} | |
case class RefF[A,B](ref:Ref[A],f:A=>B) extends Ref[B]{ | |
var v = f(ref.get) | |
override def get = v | |
registWatcher(()=>v = f(ref.get)) | |
def registWatcher(f:()=>Unit) = | |
ref.registWatcher(f) | |
} | |
object Test extends App{ | |
val a = ElemRef(List(1,2,3)) | |
val b = a.map(x=>{ | |
println("b func execute") | |
x.filter(x=>x<2) | |
}) | |
println(b.get) | |
println(b.get) | |
a.set(List(1,1,2,3,4)) | |
println(b.get) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
b func execute
List(1)
List(1)
b func execute
List(1, 1)
Process finished with exit code 0