In Haskell I want to write a recursive function that for a given list of numbers changes the sign of each element in the sublists:
list = [[1, 3, 6.7, 7.0], [], [1, 8.22, 9, 0]]
multiply (x:xs) = [n * (-1) | n <- x] : multiply xs
but I get an error:
[[-1.0,-3.0,-6.7,-7.0],[],[-1.0,-8.22,-9.0,-0.0] *** Exception: learning.hs:26:1-48: Non-exhaustive patterns in function multiply
Can anyone tell me, how can I handle an exception with empty sublists?
You've done a phenomenal job of handling the recursive step. But as in any programming language, we also need a base case to terminate recursion. Specifically, you need an explicit case for the
[]. If given[], you want your function to return[], since there's no more work to be done. ConsiderThe bottom line is exactly what you've already written. You need the second line to handle
[]input. The first line is a type signature, which, while not strictly required, is good design in Haskell and will result in better error messages if something goes wrong.