Running Elm as a Blackbox
The functional programming language Elm is best known for writing web apps. You can also use Elm to write a headless “black box” app that you talk to via the terminal. Here is a sample session:
Start the program with the command elm-bb
, then type your own commands. In this example, the commands are integers which the black box factors into primes. The set-up I will describe here has the following architecture:
On the left is the terminal, where you type your commands. Next is a 29-line Javascript program that talks to both the terminal and Main.elm
. Main.elm
imports a module Blackbox
that exposes a function
transform : String -> String
When Main.elm
receives a string input
from the terminal, it computes output = transform input
and sends this string back to the terminal. Thus, to change the behavior of the system, it suffices to change the black box. In the example above, we installed the black box using
import Factor as Blackbox
in Main.elm
. To do statistics instead of factoring integers, we would say
import Statistics as Blackbox
then recompile. Here is a session that results from this change:
There is also a :help
command, whose text is defined by helpString
in whatever black box module you import. And here is is the help screen that one includes with most black box apps:
Note that there are a number of operations for working with files. These are defined in Main.elm
, and so are available to any black box app. The command :get FILE
loads a file and stores it in memory. The command :calc
applies transform
to the contents of memory. This command can take arguments. Thus :calc col=5
calculates statistics for column 5 of the data stored in memory, while :calc col=5 rows=100:200
does the same, but only for rows 100 through 200. You can also bypass file operations entirely, applying transform
directly to data:
The code for all this is on GitHub. Just clone it, import the black box of your choice (or better, write your own). Compile with sh make.sh
Link to the global command elm-bb
with
ln -s PATH_TO/src/repl.js /usr/local/bin/elm-bb
where of course you have to set PATH_TO
. That is all there is to it!