Not logged in. Login

Exercise 4

For this exercise, put all of your function definitions in a file exer4.hs.

You must include an appropriate type declaration (::) for each function you define in your exer4.hs.

Pascal's Triangle

Write a recursive function pascal to generate the nth row of Pascal's triangle. Forget anything you might remember about combinatorics: we'll calculate the values in each row by recursively adding elements from the previous row.

*Main> pascal 0
[1]
*Main> pascal 1
[1,1]
*Main> pascal 2
[1,2,1]
*Main> pascal 3
[1,3,3,1]
*Main> pascal 12
[1,12,66,220,495,792,924,792,495,220,66,12,1]

Hint: given the previous row of Pascal's triangle prev, consider the result of

zip prev (tail prev)

Pointfree Addition

Use the curry or uncurry functions to give a pointfree (or tacit) definition of a function addPair (i.e. do not mention any arguments: define it like addPair = …).

*Main> addPair (2,3)
5
*Main> addPair (100, 3+4)
107

Pointfree Filtering

Use partial function application to give a pointfree definition of a function withoutZeros that removes any zeros from a list of numbers.

*Main> withoutZeros [1,2,0,3,4,0,5,6,0]
[1,2,3,4,5,6]
*Main> withoutZeros [0.0, 0.1, 0.2, 0.3]
[0.1,0.2,0.3]

Hint: you'll need to get the typeclasses right for the arguments. The list must have elements that are both comparable for equality (Eq, since you want to use /= on them) and are numeric (Num, since you want to compare to zero).

Searching? Maybe?

In this question, you will explore the Maybe type (which you need for assignment 1). A Maybe can be wrapped around any type and the values can either be Nothing or Just a value of that type. For example, these are some values of type Maybe Int:

Just 6
Just (-34)
Nothing

The idea behind Maybe is to handle things that might cause errors/null pointers in other languages. Basically, a function that returns a Maybe is saying “if I find an answer, I'll give it to you (wrapped in Just), but I might not find anything (Nothing)”.

Write a function findElt that returns (Just) the first position of an element in a list if it's there, and Nothing if it's not:

*Main> findElt 8 [4,5,2,8,7,3,1]
Just 3
*Main> findElt 6 [4,5,2,8,7,3,1]
Nothing
*Main> findElt 'o' "Hello World!"
Just 4
*Main> findElt 'q' "Hello World!"
Nothing

The Data.Maybe library library has some functions that might be useful. Also note that you can pattern-match on Just/Nothing values, so this is possible:

case maybeValue of
  Nothing -> …
  Just x -> …

(That might be useful, or not. I have a possible solution that uses a case, and another that uses functions from Data.Maybe. There are plenty of ways to do this.)

For this question, you have to actually do the searching yourself. i.e. no cheating with element-finding functions from Data.List or anywhere else.

Submitting

Submit your files through CourSys for Exercise 4.

Updated Fri April 28 2023, 10:19 by ggbaker.