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

# Tute Exercises Week 8

## User-defined Data Types

#### A Store for Books, Videos, and CDs

Online book sellers these days usually also sell video tapes and CDs. So, they need to maintain a product database that is flexible enough to deal with all three types of goods. In the following, we will define a module `BookVideoCD` that contains the necessary data types to deal with such a database.

First, define a data type `Product` that can represent any of the three types of goods. For each good, the following additional information has to be maintained:

• Book: the title and author
• Video: the title
• CD: the title, artist, and number of tracks

Define appropriate type synonyms for titles, authors, and artists.

#### Extract the title information from a product

Implement a function `getTitle` that, given a product, extracts its title. (Note that all three types of products contain title information.)

#### Extract titles from a product list

Now, use `getTitle` to implement `getTitles`, which, given a list of products, produces a list with all titles. There are two ways to implement this function: with an explicit recursive definition or by using the higher-order function `map`. Discuss both variants and compare them.

#### Unix permissions

Make sure that everybody understands file permissions in Unix. What is the meaning of the triplets? What are the owner and group of a file? What does execute permission imply for directories?

#### Simple shell scripts

In the lecture, we briefly discussed the following simple shell script, `hslines`, to printing the sum of the numbers of lines of all Haskell files in the current directory:

```#!/bin/sh

wc *.hs | tail -1 | cut -d ' ' -f2-2```

Discuss how it works and what the individual tools `wc`, `tail`, and `cut` do.

#### Partial functions revisited

As a preparation, recall the term partial function that we discussed earlier. So far, we raised an error whenever a partial function was applied to an argument on which it wasn't defined. An alternative would be to return a special value (let's call it `Nothing`) whenever we previously raised an error. The advantage of that is that we can actually test for the error in the calling function, rather than aborting the whole program.

Define a data type `(Maybe a)` that can be used for this purpose.

#### Safe `div`

What's the result of evaluating `10 `div` 0`? Implement a safe devision function

`safeDiv :: Int -> Int -> Maybe Int`

So that `10 `safeDiv` 0` returns `Nothing`, rather than aborting with an error message.