检查元组列表是否在Haskell中按顺序递增

时间:2016-05-10 08:42:47

标签: list haskell tuples

所以我有一个问题,我需要查看(x,y)形式的位置列表是否连续递增。

仅举几例意味着什么?

[(1,2), (1,3), (1,4), (1,5), (1,6)] it would return True, but
[(1,2), (1,3), (1,5), (1,6), (1,7)] will return False

例如,从这样开始。

is_in_order :: [Position] -> Bool

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

由于这似乎是一个练习示例,我只提供一些提示而不是完整的解决方案:

仅检查所有第二个元组是否连续是一个简单的

checkConsecutive :: Num a => [a] -> Bool
checkConsecutive x = and $ zipWith (\x y -> y - x == 1) x (drop 1 x)

但我想现在的情况应该更为一般 - 你的inOrder函数已经提供了一个很好的基线

isConsecutive :: Num a => [a] -> Bool
isConsecutive [] = True
isConsecutive [x] = True
isConsecutive (x:y:xs) = consecutive x y && isConsecutive (y:xs)
  where consecutive :: (Num a, Num b) => (a,b) -> (a,b) -> Bool
        consecutive (x1,y1) (x2,y2) = ..

你写道你需要case才能做到这一点,你可以连续使用一个案例表达式,但我认为它不会使函数更清晰。

注意:您可以将上述功能简化为

isConsecutive (x:y:xs) = consecutive x y && isConsecutive (y:xs)
  where consecutive :: (Num a, Num b) => (a,b) -> (a,b) -> Bool
        consecutive (x1,y1) (x2,y2) = ..
isConsecutive _ = True

_表示“catchall”模式 - 即匹配任何与上述模式不匹配的模式。

所以剩下的任务是声明两个元组的含义consecutive

答案 1 :(得分:0)

您可以这样实现isInOrder:

isInOrder xs = all check $ zip xs $ tail xs where
    check ((x1,y1),(x2,y2)) = x1<=x2 && y2-y1==1  

您可以按照“增加连续订单”的方式修改检查功能

相关问题