Haskell 案例中的范围检查?

发布于 2024-08-25 05:52:05 字数 201 浏览 3 评论 0原文

在 Haskell 中是否有一种有效的方法可以执行以下操作:

case n of
    0     -> doThis
    1     -> doThat
    2     -> doAnother
    3..99 -> doDefault

除了 97 行“doDefault”之外?

Is there a valid way to do the following in Haskell:

case n of
    0     -> doThis
    1     -> doThat
    2     -> doAnother
    3..99 -> doDefault

other than to have 97 lines of "doDefault" ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

懷念過去 2024-09-01 05:52:05
case n of
    0     -> doThis
    1     -> doThat
    2     -> doAnother
    _     -> doDefault

如果你确实需要一个范围,

case n of
    0     -> doThis
    1     -> doThat
    2     -> doAnother
    x | 3 <= x && x < 100 -> doDefault
    _     -> reallyDoDefault
case n of
    0     -> doThis
    1     -> doThat
    2     -> doAnother
    _     -> doDefault

If you really need a range,

case n of
    0     -> doThis
    1     -> doThat
    2     -> doAnother
    x | 3 <= x && x < 100 -> doDefault
    _     -> reallyDoDefault
彼岸花似海 2024-09-01 05:52:05

使用守卫! ;)

Foo n 
  | n == 0 = doThis
  | n == 1 = doThat
  | n == 2 = doAnother
  | (n >= 3 ) && (n <= 99) = doDefault 

或者

  | n `elem` [3..99] =  doDefault

Using guards! ;)

Foo n 
  | n == 0 = doThis
  | n == 1 = doThat
  | n == 2 = doAnother
  | (n >= 3 ) && (n <= 99) = doDefault 

OR

  | n `elem` [3..99] =  doDefault
白昼 2024-09-01 05:52:05

我认为你可以将默认情况设置为 _ 模式,它可以匹配任何内容。

case n of
  0 -> doThis
  1 -> doThat
  2 -> doAnother
  _ -> doDefault

我不确定这是否正是您正在寻找的,因为它不会检查那里范围的上限......您可能想使用守卫。

I think you can have the default case be the _ pattern, which matches on anything.

case n of
  0 -> doThis
  1 -> doThat
  2 -> doAnother
  _ -> doDefault

I'm not sure if that's quite what you're looking for, since it doesn't check the upper bound on the range there... you might want to use guards instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文