-3

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 Answers1

3

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))
K. A. Buhr
  • 45,621
  • 3
  • 45
  • 71
  • I don't want only the diagonal elements. It should include all the diagonally adjacent elements. Like for a rectangular list, index 0,1 will b adjacent to 1,2 and 1,0 – Aditi Jain Mar 22 '20 at 05:49
  • FYI I've posted a [followup question](https://stackoverflow.com/questions/60798643/testing-diagonally-adjacent-elements-in-nested-lists) including the OP's clarifications. Made the new post because it invalidates this answer somewhat. – Will Ness Mar 22 '20 at 11:19
  • @AditiJain: can you make a fair attempt and edit your question with specific questions about why that attempt is not working? – Willem Van Onsem Mar 22 '20 at 11:20
  • @AditiJain if you do come up with some code and have questions about it, please post a new question, including a link to this one for background; please do not make edits that would invalidate existing answer(s). – Will Ness Mar 22 '20 at 20:08