Skip to content
UoL CS Notes

Lecture 18-1

COMP105 Lectures

Marks to Report Example

This lecture covers a mini assignment example about converting a csv file containing students marks into a report containing the students averages. These are presented in the following format:

aaa		70	65	67	60
bbb		55	60	55	65
ccc		40	40	40	40
ddd		80	60	75	60
ccc		0	0	0	100

And should be transformed to be:

aaa		65.5
bbb		58.75
ccc		40.0
ddd		68.75
ccc		25.0

See the slides for the full examples.

Reading files in Haskell

We can read a file using readFile:

  • This is an IO function.
  • We will study this in more detail later on.
> readfile "marks.csv"
> "aaa		70	65	67	60\nbbb		55	60	55...

The \n character is the newline character.

lines

The lines function takes a string containing multiple lines into a list of strings. The complement to this function is the function unlines. This will do the opposite.

Parsing the File

Using the functions words and lines we can put the file into a list of lists of strings, in order to process the file.

Getting the Averages

The function read will convert a string into a float.

Writing the Output File

The function writeFile will write some data into a file:

> writeFile "test.txt" "hello"

This is not a pure function and we will see it again later.

All in One Function

The pure function portion of the exercise will read as the following:

report file = 
	let
		parsed		= map words . lines $ file
		students	= map name parsed
		averages	= map average parsed
		zipped		= zipWith report_line students averages
	in
		unlines zipped