tags:

views:

82

answers:

2

In scala I can write:

val pf: PartialFunction[String, Unit] = {case s => println(s)}

Now I can pass pf around, calling it with appropriate values.

I'm looking for a concise way of being able to define such a pf so that it can have a state. Say a counter of how many times it has been called. One way is this:

var counter = 0
val pf: PartialFunction[String, Unit] = {case s => counter +=1; println(s)}

What I don't like here is that it is not concise and the state is exposed.

A: 

Found this approach, though I'm not entirely happy with it:

case class PFS[S](var s: S)(pf: PartialFunction[(S,String), S]) extends PartialFunction[String, Unit] {
  override def isDefinedAt(str: String) = pf.isDefinedAt((s, str)); 
  override def apply(str: String) = {s = pf((s, str)); ()}
}

scala> val pfs = PFS("hello ") {case (s1, s2) => println(s1 + s2); s1}
pfs: PFS[java.lang.String] = <function>

scala> pfs("world")
hello world

scala> val pfs = PFS(0) {case (counter, str) => println(str + counter); counter + 1}
pfs: PFS[Int] = <function>

scala> pfs("world")
world0

scala> pfs("world")
world1

scala> pfs("world")
world2

scala> pfs("world")
world3
IttayD
+3  A: 
val pf: PartialFunction[String, Unit] = {
    var counter = 0;
    {case s =>  {
            println(counter + s)
            counter +=1
        }
    }
}
Thomas Jung