Write a function that multiplies all the positive elements in a list! I tried to make it, but I need help because it is not working. Can anybody help me what is the problem and how can I fix it?
positive :: (Num a, Ord a) => [a] -> a
positive x
| x> 0 = x * y
| otherwise = Nothing
Example:
positive [1..10] == 3628800
positive ([1..10] [-2, -5, -6]) == 3628800
positive [3, 5, 66, -8, -4, 5, 6, 93, -4567, 56] == 154677600
CodePudding user response:
You can not use x > 0, since x is a list. You can pattern match on (x:xs) for a non-empty list with x the first item, and xs the remaining items; and on [] for the empty list.
So the function should look like:
positive :: (Num a, Ord a) => [a] -> a
positive [] = … -- (1)
positive (x:xs)
| x> 0 = … -- (2)
| otherwise = … -- (3)
Where you need to fill in the … parts. The first part (1) should return a result in case of an empty list. The second (2) has a positive number x, and should recurse on the rest of the list xs and multiply the two together. Finally, the third case should recurse on the rest of the list xs, since x is less than or equal to zero.
