From HaskellWiki
< Cookbook
Revision as of 21:07, 6 January 2019 by Oliver (talk | contribs) (Fixed broken links)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Input and output

Problem Solution Examples
printing a string putStr
Prelude> putStr "Foo"
printing a string with a newline character putStrLn
Prelude> putStrLn "Foo"
reading a string getLine
Prelude> getLine
Foo bar baz          --> "Foo bar baz"

Parsing command line arguments

Command line argument processing is provided by System.Environment library.

The following small program (tac) concatenates and prints the contents of files in reverse (or reads from stdin with no arguments).

import System.Environment
import System.Exit

main = getArgs >>= parse >>= putStrLn . tac

tac = unlines . reverse . lines

parse ["-h"] = usage >> exit
parse ["-v"] = version >> exit
parse []     = getContents
parse fs     = concat `fmap` mapM readFile fs

usage   = putStrLn "usage: tac [-vh] [file..]"
version = putStrLn "Haskell tac 0.1"
exit    = exitWith ExitSuccess
die     = exitWith (ExitFailure 1)

Some example uses:

$ ./tac -h
usage: tac [-vh] [file..]

The environment

Many programs need access to computer environment variables. On POSIX systems, access to all variables is by

import System.Environment

NOTE: example uses to be added