1

Writing an interpreter for a dynamically typed language usually involves creating an Environment, a data structure which stores mappings of variable names to their values. Values are boxed in some kind of wrapper type, which might look like this in C:

typedef struct value {
  type_t type;
  void * datum;
} value_t;

where type_t explicitly stores the type of the given object. A dictionary from strings to value_t could be used as the environment for the language interpreter.

OCaml and Haskell are both strongly-typed languages, for which there are both compilers and interpreters. How do interpreters for statically typed languages differ from those of dynamically typed languages, if at all?

My first thought was that there could be one environment which maps variables to a descriptor of their types (type_t in the example above), followed by a separate environment for each type seen so far. However, I can't imagine how one would actually go about implementing such a thing. Also, after skimming the source code for the OCaml interpreter, it looks like the same kind of boxing/unboxing of values familiar from dynamic languages is used there too.

4

Of course, there's a lot of variance in how one does these things. It is generally the case though that you have two passes of the interpreter

  1. Static semantics

    This controls type checking but also might generate a more optimized intermediate form for the code to speed up interpretation later

  2. Dynamic semantics

    This actually does the evaluation and might in fact be type free. After type checking we know that the types are going to line up and so in many a statically typed language we just erase them. This means that we can represent all our values with a big union in our environment.

    Eg we have a type of all values and an map of names to that type. However, in a type safe language doing unions can be tricky so we often enforce tagged unions which have the benefit of being able to tell you what case it's in. In order to use such things we pattern match on an expression, quite a common occurrence in OCaml which I believe accounts for what you saw in their interpreter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.