Running Command Line Programs
With Haskell for Mac, most program execution during development is that of program fragments in the playground, but at some point, we want to run the whole program. In the case of a command line program, that may involve passing and parsing command line arguments, reading environment variables, and reading and writing input and output.
We can easily set command line arguments and environment variables with the functions
setEnv from System.Environment — as we do below in the playground of a simple tool to compute SHA1 hashes with the result printed to the Haskell for Mac console.
In the first invocation, we pass the name of a file,
Text.txt, whose contents we want to hash. This file is located in the "Resources" section of the project navigator. Playground code can access all files located in "Resources" using relative pathnames. (For example, the SpriteKit samples bundled with Haskell for Mac use this to access sprite image files.)
IO computations have currently —in version 1.1 of Haskell for Mac— three limitations: (1) they can't read files outside of those contained in the project, due to sandboxing, (2) they can't write files, and (3) they cannot read keyboard input from standard input (
stdin). The first two limitations will be lifted in version 1.2 of Haskell for Mac. In the meantime, we can simply execute our Haskell command line program using a terminal shell without any limitations.
This requires installing the Haskell for Mac command line tools as outlined in a previous article. Those tools include a command named
runhaskell, it runs a Haskell program in "script mode" — i.e., it is being interpreted, instead of compiled (much like, say, the Python interpreter runs a Python script).
The SHA1 example from before is contained in a Haskell for Mac project
SHA1.hsproj whose main Haskell file is
SHA1.hs. In the following Terminal session, it presents a prompt, and then, reads the text to be hashed from standard input.
Download our running example, SHA1.hsproj, and try for yourself!