Functional Programming – Writing a Small Interpreter

functional programmingshellunix

I'm working on a small Unix shell, and am contemplating the idea of writing a script interpreter. While reading about the subject I inevitably hear of functional programming, lambda calculus, and find out about the whole fascination around Lisp.

Before I jump into this I have some questions.

  • Which language should I use?

I am curious about functional programming, so that would be a great opportunity to start. I want my shell to have as little 3rd party dependencies as possible. I am wondering whether I should look for a compiled language. I would like being able to distribute it more easily. Is this a correct approach? if so, which language would you recommend?

  • How do you embed an interpreter in your program?

The way I see it is having the interpreter run in a second separate process. As far as I know, two processes communicating, are either listening to a pipe or sending signals to one another. Is this a realistic approach? Is there a particular language that handles this part? Are there other ways of embedding the interpreter?

Best Answer

You should probably use ANSI C. It's universal across all platforms. It's low level and has system-level interfaces for everything on all platforms which will be required for a scripting runtime or programming language.

To write a script interpreter, I would suggest reading the Dragon Book [1] first. It's pretty math heavy but the basics are easy enough to pick up. If you are interested in LISP/Scheme, read SICP [2]. Both books describe interpretation and compilation in depth in two different contexts. SICP will change your life if you are interested in programming languages.

Regarding embedding, your script interpreter should probably have an "eval" function which takes a string in your language, executes it and returns a result. That is the only entry point you should need for embedding.

UNIX/Linux/OSX does all the communication stuff for you using pipes etc. Just concentrate on something which talks to stdin and stdout and you will be sorted. Even works (mostly) on Windows.

Start really simple. This is as simple as you need to start ([3]). It implements a complete LISP interpreter in C in not much code at all.