【问题标题】:Check if tuple list is in increasing consecutive order in Haskell检查元组列表是否在 Haskell 中连续增加顺序
【发布时间】:2016-09-05 03:01:07
【问题描述】:

所以我有一个问题,我需要查看 (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

感谢您的帮助。

【问题讨论】:

  • 你已经尝试过什么?列表[(1,2),(2,1)] 是什么?
  • 顺便说一句,haskell 通常使用 camelCase,因此命名 is_in_order 通常是 isInOrder,我建议使用 HLint 来检查类似的常见内容 - 它帮助我提高了我的 Haskell 技能!
  • 谢谢@epsilonhalbe 我会把它改成isInOrder。所以我刚刚尝试了isInOrder :: (Ord a) => [a] -> Bool isInOrder [] = True isInOrder [x] = True isInOrder (x:y:xs) = x <= y && isInOrder (y:xs) 这只是整理了一个列表。我似乎无法让它与元组一起使用,我需要它以案例格式
  • unzip [(1,2), (1,3)] == ([1,1], [2,3]) 可能会有所帮助。
  • 您只检查这些元组的y 值吗?还是x 也起到了一些作用?

标签: list haskell tuples


【解决方案1】:

您可以通过这种方式实现 isInOrder:

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

您可以修改检查功能,就像'增加连续订单'的方式

【讨论】:

    【解决方案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才能做到这一点,你可以连续使用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 的含义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      • 2013-04-27
      • 1970-01-01
      • 2016-05-02
      • 1970-01-01
      • 2017-05-04
      相关资源
      最近更新 更多