Homework 2
Due on Oct 5 Wednesday

## 1. What are the types of the following values?

1. [’a’,’b’,’c’]

2. (’a’,’b’,’c’)

3. [(False,’0’),(True,’1’)]

4. ([False,True],[’0’,’1’])

5. [tail,init,reverse]

## 2. What are the types of the following functions?

1. second xs = head (tail xs)

2. swap (x,y) = (y,x)

3. pair x y = (x,y)

4. double x = x*2

5. palindrome xs = reverse xs == xs

6. twice f x = f (f x)

## 3. Types and Typeclasses

1. What functions define the typeclasses Real and Integral, respectively? Read the documentation (find them either through Hayoo or Hoogle) of these functions and try invoking each of them in ghci. Show your trials and explain in English what the functions do.

2. What are the example types that are instances of Real and Integral, respectively. Try invoking the Real and Integral functions on values of the example types that you give.

3. Define a function f as follows:

f x = toRational \$ rem x 5
1. What is f's type?

2. Describe how would your Haskell compiler/interpreter infer f's type.

## 4. Functions

1. Redefine the following version of (&&) using conditionals rather than patterns:

True && True = True
_    && _    = False
2. Give three possible definitions for the logical or operator (||) using pattern matching.

3. What does the init function in Prelude1 do? Define init in terms of functions length and take.

## 5. List Comprehension

1. The scalar product of two lists of integers xs and ys of length n is give by the sum of the products of the corresponding integers:

(1)

Using a list comprehension, define a function that returns the scalar product of two lists. (Hint: You could start from the following program stub.)

 scalarProduct :: [Int] -> [Int] -> Int
scalarProduct xs ys = undefined
2. A positive integer is perfect if it equals the sum of all of its factors, excluding the number itself. Using a list comprehension, define a function

perfects :: Int -> [Int]
perfects n = undefined

that returns the list of all perfect numbers up to a given limit, such that, e.g.:

Prelude λ> perfects 500
[6,28,496]

1.Prelude is a standard module loaded by default when you start ghci. Information about Prelude can be found on the Prelude Hackage page.