Thursday, February 28, 2019

HASKELL COMMAND LINE ARGUMENTS

HASKELL COMMAND LINE ARGUMENTS

REVISED: Wednesday, January 24, 2024


1. INTRODUCTION

Haskell code can be run interactively using GHCi or compiled to an executable using GHC. A command-line is a line of code used to compile a Haskell program using the GHC compiler.

2. OVERVIEW

In Haskell, you can access the command-line arguments with the function getArgs. Import System.Environment to get access to the getArgs function. The getArgs function is not interactive. It will just return the arguments supplied from the command-line, if any were supplied. If you do not supply any arguments at the command-line, then the returned list will be empty as shown in Example 1 below.

Command-line arguments used in GHC are either options or file names. Command-line options begin with -. Command-line options are order-dependent, with arguments being evaluated from left-to-right.

3. EXAMPLE 1

GHCi, version 9.8.1: http://www.haskell.org/ghc/  :? for help
Prelude> :m + System.Environment
Prelude System.Environment> :t getArgs
getArgs :: IO [String]
Prelude System.Environment> do a <- getArgs; print a
[]     -- Empty, because we did not provide any arguments.
Prelude System.Environment> 

4. EXAMPLE 2

This is an example of a program loaded into GHCi and run interactively.

-- Program Name: Interactive.hs

add x y = x + y

total [] = 0
total [x] = x
total (x:xs) = add x (total xs)

compute xs = show $ total $ map read xs

main = do
    putStrLn "Enter first number."
    num1 <- getLine
    putStrLn "Enter second number."
    num2 <- getLine
    putStrLn "Enter last number."
    num3 <- getLine
    putStrLn $ "Total is: " ++ compute [num1, num2, num3]

Prelude> :l Interactive.hs
[1 of 1] Compiling Main             ( Interactive.hs, interpreted )
Ok, one module loaded.
*Main> main
Enter first number.
3
Enter second number.
5
Enter last number.
7
Total is: 15
*Main> 


5. CONCLUSION

A programmer can automate the execution of a program by using command-line arguments in GHC when they compile their Haskell program.


6. REFERENCES

Bird, R. (2015). Thinking Functionally with Haskell. Cambridge, England: Cambridge University Press.

Davie, A. (1992). Introduction to Functional Programming Systems Using Haskell. Cambridge, England: Cambridge University Press.

Goerzen, J. & O'Sullivan, B. &  Stewart, D. (2008). Real World Haskell. Sebastopol, CA: O'Reilly Media, Inc.

Hutton, G. (2007). Programming in Haskell. New York: Cambridge University Press.

Lipovača, M. (2011). Learn You a Haskell for Great Good!: A Beginner's Guide. San Francisco, CA: No Starch Press, Inc.

Thompson, S. (2011). The Craft of Functional Programming. Edinburgh Gate, Harlow, England: Pearson Education Limited.