表达式中的组匹配

时间:2013-03-02 10:46:07

标签: haskell

我有一个像

这样的变量
a = 3

对于a的某些值,我有相同的函数我想调用:

case a of
     3 -> print "hello"
     4 -> print "hello"
     5 -> print "hello"
     6 -> print "hello something else"

因此,对于a = 3,a = 4且a = 5,我进行相同的函数调用。 我能把这些组合得更好吗?我正在寻找一个解决方案:

case a of
     3 || 4 || 5 -> print "hello"
     6           -> print "hello something else"

这当然不起作用,但希望你能达到我想要的目的。

感谢。

2 个答案:

答案 0 :(得分:13)

怎么样

case a of
     _ | a == 3 || a == 4 || a == 5
       -> print "hello"
     6 -> print "hello something else"

写作不那么乏味

case a of
     _ | a `elem` [3, 4, 5]
       -> print "hello"
     6 -> print "hello something else"

case a of
     _ | 3 <= a && a <= 5
       -> print "hello"
     6 -> print "hello something else"

甚至,如果在你的真实程序中有很多可能的值可供你匹配,就像这样:

import qualified Data.Set as S

valuesToMatchAgainst :: S.Set Int
valuesToMatchAgainst = S.fromList [3, 4, 5]

-- ...

    case a of
         _ | a `S.elem` valuesToMatchAgainst
           -> print "hello"
         6 -> print "hello something else"

(我假设你已经明白_是一个匹配任何值的通配符,| introduces a guard。)

答案 1 :(得分:2)

您可以执行不同的操作来改进代码。首先,如果所有分支调用相同的函数,那么为什么不:

print (case a of 
         3 -> "hello"
         4 -> "hello"
         5 -> "hello"
         6 -> "hello something else")

这会导致更多代码的常见行为。其次,您似乎要求将3,4和5个案例分组在一起,最好的方法可能是分解函数:

 let cat 3 = True
     cat 4 = True
     cat 5 = True
     cat 6 = False
 in print (case cat a of True -> "hello"
                         False -> "hello something else")

您可以将其与上一张海报(cat x = x elem [3,4,5]等建议的其中一种替代方法相结合。