Convert expression to polish notation in Scala

359 views Asked by At

I would like to convert an expression such as: a.meth(b) to a function of type (A, B) => C that performs that exact computation.

My best attempt so far was along these lines:

def polish[A, B, C](symb: String): (A, B) => C = { (a, b) =>
// reflectively check if "symb" is a method defined on a
// if so, reflectively call symb, passing b
}

And then use it like this:

def flip[A, B, C](f : (A, B) => C): (B, A) => C = {(b, a) => f(a,b)}
val op = flip(polish("::"))
def reverse[A](l: List[A]): List[A] = l reduceLeft op

As you can pretty much see, it is quite ugly and you have to do a lot of type checking "manually".

Is there an alternative ?

1

There are 1 answers

1
lambdas On

You can achieve it easily with plain old subtype polymorphism. Just declare interface

trait Iface[B, C] {
    def meth(b: B): C
}

Then you could implement polish easily

def polish[B, C](f: (Iface[B, C], B) => C): (Iface[B, C], B) => C = { (a, b) =>
    f(a, b)
}

Using it is completely typesafe

object IfaceImpl extends Iface[String, String] {
    override def meth(b: String): String = b.reverse
}

polish((a: Iface[String, String], b: String) => a meth b)(IfaceImpl, "hello")

Update:

Actually, you could achieve it using closures only

def polish[A, B, C](f: (A, B) => C): (A, B) => C = f

class Foo {
  def meth(b: String): String = b.reverse
}

polish((_: Foo) meth (_: String))(new Foo, "hello")

Or without helper function at all :)

val polish = identity _ // Magic at work

((_: Foo) meth (_: String))(new Foo, "hello")