Haskell嵌套列表 [英] Haskell nested lists
问题描述
我是Haskell编程的新手,我正在尝试检查嵌套列表中对角相邻的元素是否互不为负. 我的职能是:
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
示例:checkNegation[[1,2], [3, -1]]
将返回False
checkNegation [[1,2],[-1,3]]
将返回True
.
Example: checkNegation[[1,2], [3, -1]]
will return False
checkNegation [[1,2],[-1,3]]
will return True
.
推荐答案
我建议将问题分解为几个步骤.
I would suggest breaking the problem into steps.
第1步:编写一个函数以获取对角线元素:
Step 1: Write a function to get the diagonal elements:
diag :: [[a]] -> [a]
您可能会发现此问题很有帮助.
You may find this question helpful.
第2步:您想检查结果列表中的相邻元素是否彼此相反:
Step 2: You'd like to check if the adjacent elements of the resulting list are negatives of each other:
allAdjNeg :: [Int] -> Bool
其中allAdjNeg [-1,1,-1,1] = True
.
这也可以很容易地逐步完成.在步骤2(a)中,检查每对相邻的元素.您也许可以将答案调整为这个问题来编写一个函数:
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]
提示:如果定义一个函数isNeg x y = x == -y
,则它是一个类似于(-)
的二进制运算符,并且可以与zipWith
相同的方式使用.
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.
在步骤2(b)中,您想查看adjNeg
返回的列表[Bool]
是否为True. and :: [Bool] -> Bool
功能在这里将很有帮助.那应该允许您定义allAdjNeg
.
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))
这篇关于Haskell嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!