logo       

Re: Type inferencing pattern matching anonymous functions: msg#00468

lang.scala

Subject: Re: Type inferencing pattern matching anonymous functions

Replying to my own question, just to make sure the solution is archived.

On 1/26/07, Rafael de F. Ferreira <rafael@xxxxxxxxxxxxxxxxxx> wrote:
I hit a problem when dealing with {case P => R ...} expressions and
wanted to ask if anyone has found a better solution. I wrote the
following helper function:
def replace[T](l:List[T], f:PartialFunction[T,T]) : List[T] = l match {
case Nil => Nil
case x::xs => (if (f.isDefinedAt(x)) f(x) else x) :: replace(xs, f);
}

The idea is to call it with a {case ...} function as the second
parameter like this:
case class Something(i:int)
val double1 = replace(original, {case Something(2) => Something(4)})
//error here

That didn't work because the compiler can't figure out the type of the
function (a "missing parameter type" error is reported). If it is
explicitly supplied to replace() then no compilation errors occur:
val double2 = replace[Something](original, {case Something(2) =>
Something(4)}) //OK

The best solution I could find to retain the generality without being
too verbose is to curry the type argument before the call site:
def replSomething = &replace[Something];
...
val double3 = replSomething(original, {case Something(2) => Something(4)})

Has anyone got a better idea?
I do :-)

Inspired by Martin's message to the list explaining the foldLeft
syntax, I changed the method declaration to "explicitly" curry the
second parameter. This way the compiler is able to infer the correct
type of the anonymous function being passed. It ended up like this:

def replace[T](l:List[T])(f:PartialFunction[T,T]) : List[T] = l match {
case Nil => Nil
case x::xs => (if (f.isDefinedAt(x)) f(x) else x) :: replace(xs)(f);
}

case class Something(i:int)
val original = List(Something(1), Something(2), Something(3))
val double1 = replace(original){case Something(2) => Something(4)}


Thanks a lot;
--
Rafael de F. Ferreira.
http://www.rafaelferreira.net/


--
Rafael de F. Ferreira.
http://www.rafaelferreira.net/



<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise