• Home
  • Textbooks
  • Programming in Haskell
  • Defining functions

Programming in Haskell

Graham Hutton

Chapter 4

Defining functions - all with Video Answers

Educators


Chapter Questions

Problem 1

Using library functions, define a function halve :: [a] $\rightarrow([a],[a])$ that splits an even-lengthed list into two halves. For example:
$$\begin{aligned}
& >\text { halve }[1,2,3,4,5,6] \\
& ([1,2,3],[4,5,6])
\end{aligned}$$

Check back soon!
01:52

Problem 2

Define a function third :: [a] $\rightarrow$ a that returns the third element in a list that contains at least this many elements using:
a. head and tail;
b. list indexing !!;
c. pattern matching.

Goutam Chand
Goutam Chand
Numerade Educator
01:07

Problem 3

Consider a function safetail :: [a] $\rightarrow$ [a] that behaves in the same way as tail except that it maps the empty list to itself rather than producing an error. Using tail and the function null :: [a] $\rightarrow$ Bool that decides if a list is empty or not, define safetail using:
a. a conditional expression;
b. guarded equations;
c. pattern matching.

Vysakh M
Vysakh M
Numerade Educator

Problem 4

In a similar way to $\& \&$ in section 4.4 , show how the disjunction operator ? can be defined in four different ways using pattern matching.

Check back soon!
01:42

Problem 5

Without using any other library functions or operators, show how the meaning of the following pattern matching definition for logical conjunction \&\& can be formalised using conditional expressions:
True \&\& True $=$ True
- $\& \&$ _ $=$ False
Hint: use two nested conditional expressions.

John Mcalister
John Mcalister
Numerade Educator
01:00

Problem 6

Do the same for the following alternative definition, and note the difference in the number of conditional expressions that are required:
$$\begin{aligned}
& \text { True \&\& b=b } \\
& \text { False \&\&_ }=\text { False }
\end{aligned}$$

Harsh Gadhiya
Harsh Gadhiya
Numerade Educator
00:59

Problem 7

Show how the meaning of the following curried function definition can be formalised in terms of lambda expressions:
$$\begin{aligned}
& \text { mult : : Int } \rightarrow \text { Int } \rightarrow \text { Int } \rightarrow \text { Int } \\
& \text { mult } x \text { y } z=x^{\star} y^{\star} z
\end{aligned}$$

Vikash Ranjan
Vikash Ranjan
Numerade Educator

Problem 8

The Luhn algorithm is used to check bank card numbers for simple errors such as mistyping a digit, and proceeds as follows:
- consider each digit as a separate number;
- moving left, double every other number from the second last;
- subtract 9 from each number that is now greater than 9 ;
- add all the resulting numbers together;
- if the total is divisible by 10 , the card number is valid.
Define a function luhnDouble :: Int $\rightarrow$ Int that doubles a digit and subtracts 9 if the result is greater than 9. For example:

Check back soon!