3

Possible Duplicate:
“eval” in Scala

Dr. Subramaniam in his presentation http://www.youtube.com/watch?v=LH75sJAR0hc at min 30 when he starts talking about functional style in Scala he gives this example

class Car {
  def turn(direction: String) = {
    println("turning " + direction)
  }
}

val car = new car
car turn "left"

and then he says that the last line could be read from a data file and evaluated. So, data becomes code, code becomes data.

How does Scala supports this? Does it have an eval function?

Community
  • 1
  • 1
Nabegh
  • 3,249
  • 6
  • 25
  • 26
  • Ever heard of a hashtable? Put your string commands in a hashtable with corresponding actions (functions) as values. – Marcin May 15 '12 at 12:25
  • +Marcin, that's an implementation detail. You're still writing an interpreter. And there are many ways to do that. – Don Stewart May 15 '12 at 13:27
  • @DonStewart I think it's an abuse of language to describe every function that accepts strings or tokens to trigger behaviour as an interpreter. In any case, it's not a mere detail that it is very easy to implement this sort of thing in a language with first-class functions. – Marcin May 15 '12 at 13:49

1 Answers1

1

Pretty much every language supports an eval function (even strongly, statically typed languages like Haskell). Many language runtimes built for languages that are primarily implemented via bytecode interpretation (such as Lisp-like languages, Erlang or Java) support the ability to insert new (byte)code at runtime.

Once you can insert new code dynamically, you can write eval.

Scala is an example of such a language, where the JVM is available at runtime.

Even in language implementations without specific support for full meta-programming, or even dynamic linking, there are often ways to dynamically generate code under programmer control, either via reflection mechanisms or code generation support libraries (such as LLVM).

Beyond just a simple one-stage eval, more generally, languages that support multi-stage computation allow for generation of programs from one stage to the next, for arbitrary numbers of stages, making it possible to safely, arbitrarily nest evals.

Background reading

Don Stewart
  • 137,316
  • 36
  • 365
  • 468