0
votes

I am new to Haskell so I'm trying to understand high order functions and how they work using map, filter, foldr, foldl, foldr1, foldl1, and operator.

First I wanted to start with a function that multiplies elements in a list and multiplying an empty list returns 1.

I have this so far, but I'm not sure where to go next.

mult :: [Int] -> Int
2

2 Answers

4
votes

Start with explicit recursion first... that means do not use foldl/foldr and friends.

Let's start by handling the corner case of an empty list:

mult [] = 1

Now, we can do something to the first element of a list by doing:

mult (x:xs) = x * 3

x is the first element of the list, while xs is the remaining list. So this just multiplies the first element of your list with 3. Now you have to figure out what to replace 3 with in order to make the whole thing do what you want. The rest is already correct, as in:

mult :: [Int] -> Int
mult [] = 1
mult (x:xs) = x * <this part is missing, recursion maybe?>
3
votes

You should handle the case of an empty list:

mult [] = ?

Then, what are you trying to do? You want to basically take a list:

[1, 2, 3, 4]

And insert multiplication symbols in between:

1 * 2 * 3 * 4

I would recommend you look into how fold works.