【问题标题】:using guard inside where bindings in Haskell language在 Haskell 语言的 where 绑定中使用守卫
【发布时间】:2021-07-11 07:02:36
【问题描述】:

我是 Haskell 语言的新手,我想在 where binding 中使用 guard,但出现错误: 不在范围内:`x' 失败,已加载模块:无。

describelist'' :: [a] ->String
describelist'' xs = "the list is : " ++ what xs
    where what xs
              | xs == "" = "empty list "
              | xs ==[x] = "singleton"
              | otherwise = "list more than or equal two elements"

我认为我的代码是正确的,但总是出现错误,

【问题讨论】:

  • xs == [x] 没有意义(作为守卫),因为您没有定义 x,这是一种模式。

标签: haskell


【解决方案1】:

xs == [x] 作为 guard 毫无意义,因为您没有定义 x,这是一种模式。 xs == ""也一样,因为没有说xsString,比如可以是Ints的空列表。

因此你应该使用模式匹配:

describelist'' :: [a] -> String
describelist'' xs = "the list is : " ++ what xs
    where what [] = "empty list"
          what [_] = "singleton"
          what _ = "list more than or equal two elements"

【讨论】:

  • 感谢您的帮助,现在有点理解我的误解了。为了更清楚地了解这个概念,我还有一个问题是:“ guard 用于与特定值的模式匹配?这是 guard 和 模式匹配
  • @LeoPkm:守卫是一个计算结果为Bool的表达式,它不能引入新变量。
  • @LeoPkm 当您有一个给定类型的值(例如一个列表)并且您需要测试该值时,您应该首先尝试使用构造函数进行模式匹配([](x:xs),例如列表)。这不仅会检查哪个表单具有您的价值,还会将价值分解成各个部分(定义xxs)。如果这还不够,您还可以添加警卫。我建议不要使用守卫,除非你找不到任何使用模式匹配的解决方案。
猜你喜欢
  • 1970-01-01
  • 2012-10-30
  • 1970-01-01
  • 2018-04-03
  • 2017-07-26
  • 2020-05-03
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多