Haskell nested lists

410 views Asked by At

I'm new to haskell programming and I'm trying to check if the diagonally adjacent elements in the nested lists are not negative of each other. I have my function as:

checkNegation :: [[Int]] -> Bool

Example: checkNegation[[1,2], [3, -1]] will return False checkNegation [[1,2],[-1,3]] will return True.

1

There are 1 answers

4
K. A. Buhr On

I would suggest breaking the problem into steps.

Step 1: Write a function to get the diagonal elements:

diag :: [[a]] -> [a]

You may find this question helpful.

Step 2: You'd like to check if the adjacent elements of the resulting list are negatives of each other:

allAdjNeg :: [Int] -> Bool

where allAdjNeg [-1,1,-1,1] = True.

This, too, might be most easily done in steps. In step 2(a), check each pair of adjacent elements. You may be able to adapt the answer to this question to write a function:

adjNeg :: [Int] -> [Bool]

Hint: If you define a function isNeg x y = x == -y, this is a binary operator just like (-) and can be used with zipWith in the same way.

In step 2(b), you want to see if the list [Bool] returned by adjNeg is all-True. The and :: [Bool] -> Bool function will be helpful here. That should allow you to define allAdjNeg.

Then, your final function will be something like:

checkNegation :: [[Int]] -> Bool
checkNegation lsts = not (allAdjNeg (diag lsts))