【问题标题】:haskell function gap that takes in list of elements and returns true if gaphaskell 函数 gap 接受元素列表并在 gap 时返回 true
【发布时间】:2021-05-13 14:30:21
【问题描述】:

我正在尝试创建一个 haskell 函数,该函数接受元素列表,如果有空格则返回 true,如果没有则返回 false。

这就是我所拥有的,在运行测试时它返回全部为真。当前 2 种情况应该为假时。

gaps :: (Enum t, Eq t) => [t] -> Bool
gaps [] = False
gaps [x] = False
gaps (x:y:xs) = if y == (succ x) then gaps (y:xs) else True

gapsTests = [
          not $ gaps [1..10]
         ,not $ gaps "ABCD"
         ,gaps "ABD"
         ,gaps [1,2,3,5,6]
         ,gaps "ABBC"
        ]

【问题讨论】:

  • 注意前面的not,如果没有空格,not $ gaps [1..10] 将返回True
  • 所以它应该都返回True?我没有意识到不是
  • 使用 not 意味着您可以使用 and gapsTests 而不是 gapsTests == [False, False, True, True, True] 之类的方式验证所有测试。

标签: haskell


【解决方案1】:

前两种情况也返回True,因为我们在前面使用not $。因此,我们检查[1..10] 是否有no 间隙,"ABCD" 是否有no 间隙,这两种情况都成立:

gapsTests = [
    not $ gaps [1..10]   -- check if the list does not contain any gaps
  , not $ gaps "ABCD"    -- check if the list does not contain any gaps
  , gaps "ABD"           -- check if the list does contain any gaps
  , gaps [1,2,3,5,6]     -- check if the list does contain any gaps
  , gaps "ABBC"          -- check if the list does contain any gaps
  ]

这意味着您的gapsTests 的所有项目都应该是True。如果是这样,则测试成功。

【讨论】:

    【解决方案2】:

    您可以通过与您期望找到的列表进行比较来避免自己进行递归和案例分析,[x..y]

    gaps :: (Enum t, Eq t) => [t] -> Bool
    gaps [] = False
    gaps xs@(x:_) = not (and (zipWith (==) xs [x..]))
    

    【讨论】:

      【解决方案3】:

      if A then B else Trueif not A then True else B 相同,not A || B 相同。

      因此,您可以将代码重写为

      gaps :: (Enum t, Eq t) => [t] -> Bool
      gaps (x:y:xs)  =  (y /= succ x) || gaps (y:xs)
      gaps _  =  False
      

      那么,

      > gaps [1..10]
      False                         -- no gaps
      
      > gaps "ABC"
      False                         -- no gaps
      
      > gaps ("ABD" ++ undefined)
      True                          -- there's a gap here
      

      仅访问输入以获得结果所需的尽可能多的元素。他被称为“懒惰的评价”。

      【讨论】:

        猜你喜欢
        • 2011-05-12
        • 2018-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-11
        • 1970-01-01
        • 2013-03-24
        相关资源
        最近更新 更多