COMP1011 Exercises for Week 07
Computing 1A 05s2 Last updated Tue 19 Jul 2005 14:37
Mail cs1011@cse.unsw.edu.au

Tute Exercises Week 7

Input & Output

Using an interpreter versus standalone programs

Discuss how entering the expression 3 + 4 at GHCi's prompt is different from compiling and executing the following Haskell module:

module Main
where

main :: IO ()
main  = print (3 + 4)

Discuss the idea of an interpreter eval-print loop and how it is useful for debugging programs. Contrast this to compiled programs and how they are more convenient for the end-user, but always require explicit I/O. If the above program where in a file Tut_io_1.hs, we would compile it with the command

ghc -o tut_io_1 Tut_io_1.hs

at a Unix shell prompt. Make sure that the usage of ghc is clear and how we can execute compiled programs.

Computation versus interaction

Why does

aString :: String
aString  = "This is a string constant"

have type String, but the function getLine have type IO String? Discuss how a complete programs consist out of a computational kernel and an interaction shell, where the latter manages the information flow between the computations encoded in the program and the "outside world."

A small interactive program

Write a program that queries two number from the user, and then, prints their sum:

enki chak 15 (.../html/tutes): ghc -o tut_io_2 Tut_io_2.hs
enki chak 16 (.../html/tutes): ./tut07_2
Enter first number: 3
Enter second number: 4
7

Important Hint: Import the module IO and use the statement hSetBuffering stdout NoBuffering as the first action in main to allow output and input on the same line.

Write two versions of the program: one using readLn and the other using getLine and read. Discuss the difference.

Write another program that accepts a list of numbers (in Haskell's list syntax) and outputs the sum:

enki chak 20 (.../html/tutes): ghc -o tut_io_3 Tut_io_3.hs
enki chak 21 (.../html/tutes): ./tut07_3
Enter a list of numbers: [4,2,7,4,5,0]
22