[Haskell-cafe] FW: Treating command-line arguments as a Haskell expression

Yitzchak Gale gale at sefer.org
Mon Dec 24 09:41:28 EST 2007

Simon Peyton-Jones:
>> Would someone familiar with the command-line-parsing libraries
care to help Krassimir?

I agree with Max that it looks like the problem is
not doing any fancy command-line parsing
(if that is indeed the issue, then please post more
information about what the problem is).
Rather, how to run a function whose name
and arguments are given as strings from
the command line.

Max gave one answer. Another approach,
if appropriate, would be to use GHCi.
You could do that using the GHC API:


(search for "runStmt")

Or you could do it using GHCi from the command line
and the shell. This is a bit of a hack, but you can get it
working in minutes, without installing anything extra.
Here's how:

The trick is to pass information into GHCi via
environment variables, using the .ghci file and
the :def command.

Place something like the following in the file ".ghci"
in the same directory with your program:

:def getEnv (\[v,e]->System.Environment.getEnvironment>>=return.maybe""((concat["let
",v,"="]++).show).lookup e).words
:getEnv func FUNC
:getEnv args ARGS
:def run const(return$unwords[func,args])

(Watch out for word-wrap in this email message - there needs
to be a space after the word "let ", and every line begins
with ":")

Write a simple shell script that arranges for the
name of the function and arguments to be in
the environment variables FUNC and ARGS,
and then calls ghci. Something like this
(assuming you are on something Unix-like):


export FUNC="$1"
export ARGS="$*"
ghci YourProgram.hs

This obviously would have to be tweaked to
your specific needs. For example, you'll get
the GHCi welcome message at the beginning
of your output. So your shell script will have
to filter that out if it is not acceptable.

Hope this helps,

More information about the Haskell-Cafe mailing list