# Exercises

## 02. Starting Out

Using IHaskell: https://github.com/gibiansky/IHaskell

The first function has been completed as an example. All the other functions are undefined. They can be implemented in one line using the material covered in http://learnyouahaskell.com/starting-out

All indices are zero based.

### 1. Find the penultimate element in list l

``````

In [1]:

penultimate l = last (init l)

-- Test:
penultimate [1,4,10,11,22] == 11

``````
``````

True

``````

### 2. Find the element at index k in list l

For example: "`findK 2 [0,0,1,0,0,0]`" returns `1`

``````

In [ ]:

findK k l = undefined

-- Test:
findK 2 [0,0,1,0,0,0] == 1

``````

### 3. Determine if list l is a palindrome

``````

In [ ]:

isPalindrome l = undefined

-- Test:
isPalindrome "anna" && not (isPalindrome "anne")

``````

### 4. Duplicate the elements in list xs

For example "`duplicate [1,2,3]`" would give the list `[1,1,2,2,3,3]`

Hint: The "`concat [l]`" function flattens a list of lists into a single list.

• You can see the function definition by typing ":t concat" into the interpreter. Perhaps try this with other variables and functions

• For example: `concat [[1,2,3],[3,4,5]]` returns `[1,2,3,3,4,5]`

``````

In [ ]:

duplicate xs = undefined

-- Test:
duplicate [1,2,3] == [1,1,2,2,3,3]

``````

### 5. Imitate the functinality of zip

For example "`ziplike [1,2,3] ['a', 'b', 'c', 'd']`" returns `[(1,'a'), (2, 'b'), (3, 'c')]`

Hint: the function "`min x y`" returns the lower of values x and y

``````

In [ ]:

ziplike xs ys = undefined

-- Test:
ziplike [1,2,3] ['a', 'b', 'c', 'd'] == [(1,'a'), (2, 'b'), (3, 'c')]

``````

### 6. Split a list l at element k into a tuple: The first part up to and including k, the second part after k

For example "`splitAtIndex 3 [1,1,1,2,2,2]`" returns `([1,1,1],[2,2,2])`

``````

In [ ]:

splitAtIndex k l = undefined

-- Test:
splitAtIndex 3 [1,1,1,2,2,2] == ([1,1,1],[2,2,2])

``````

### 7. Drop the element at index k in list l

For example "`dropK 3 [0,0,0,1,0,0,0]`" returns `[0,0,0,0,0,0]`

``````

In [ ]:

dropK k l = undefined

-- Test:
dropK 3 [0,0,0,1,0,0,0] == [0,0,0,0,0,0]

``````

### 8. Extract elements between ith and kth element in list l. Including i, but not k

For example, "`slice 3 6 [0,0,0,1,2,3,0,0,0]`" returns `[1,2,3]`

``````

In [ ]:

slice i k l = undefined

-- Test:
slice 3 6 [0,0,0,1,2,3,0,0,0] == [1,2,3]

``````

### 9. Insert element x in list l at index k

For example, "`insertElem 2 5 [0,0,0,0,0,0]`" returns `[0,0,0,0,0,2,0]`

``````

In [ ]:

insertElem x k l = undefined

-- Test:
insertElem 2 5 [0,0,0,0,0,0] == [0,0,0,0,0,2,0]

``````

### 10. Rotate list l n places left

For example, "`rotate 2 [1,2,3,4,5]`" gives `[3,4,5,1,2]`

``````

In [ ]:

rotate n l = undefined

-- Test
rotate 2 [1,2,3,4,5] == [3,4,5,1,2]

``````