This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Fwd: Implicit parameter to partial functions?

No replies
mailleux
Joined: 2008-08-23,
User offline. Last seen 4 years 7 weeks ago.
On Fri, Jan 30, 2009 at 3:41 AM, Paul Phillips <paulp [at] improving [dot] org> wrote:
On Thu, Jan 29, 2009 at 09:33:25PM -0200, Thomas Sant Ana wrote:
> Is there a way to specify implicit parameter to a partial Function?

I'm not all that optimistic this will accomplish what you want, but here's what I came up with:

scala>   case class PF(implicit prefix: String) extends PartialFunction[String,Int] {
    |     def isDefinedAt(x: String): Boolean = x startsWith prefix
    |     def apply(x: String) = if (isDefinedAt(x)) x.length else throw new MatchError(x)
    |   }
defined class PF

That is to restrictive, my problem is the following. I have a actor that received messages. I implemented a way of doing undo and redo on messages. This involves several things including a Transaction, TransactionLog and Undoable containters.

The undoable have a value with setters:

class Undoable[T](init:T)  {
   private var v=init
   def value= v
   def value_=(n:T)(implicit trans:Transaction) = { v=n, trans.addMemento(this) }
} // TO make it short


Now in the actor I have:
class X extends Actor {

val data= new Undoable[Int](10)

implicit trans=new Transaction()
react {
    case msg1(v)=> data.value=v
}

This works ok. The problem is that I'd like to have a way of making the react more modular, an I need to "forward" the implicit transction to it.

What I managed to come up with was:

abstract class Handler[A,B,T<:AnyRef] extends PartialFunction[A,B] {
  implicit var context:T=null.asInstanceOf[T]
  val pf:PartialFunction[A,B]
 
  def isDefinedAt(x:A) = pf.isDefinedAt(x)
  def doit(x:A)(implicit i:T):B = {
    context=i
    val r=pf.apply(x)
    context=null.asInstanceOf[T]
    r
  }
  def apply(x:A):B = { throw new Exception("No context specified")}
}



object PartialFunctionTrans {
  def main(args : Array[String]) : Unit = {
    val h1 = new Handler[Int,Unit,String] {
      override val pf:PartialFunction[Int,Unit]= {
        case 10 => println("yes"+context)
      }
    }
   
    try {
      h1(10)
    } catch {
      case s=> println("This was expected")
    }
   
   
   
    implicit val name="Thomas"
   
    h1.doit(10)
}

Any better ways of doing this?

Thomas

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland