评估和收集条件的结果

时间:2014-11-13 04:11:02

标签: haskell if-statement functional-programming pattern-matching

我有一堆返回列表的条件,有没有一种方法来评估它们而不给每个条件命名?

简化示例:

conditions i j = c1 i j ++ c2 i j ++ c3 i j

    where 
    c1 i j | i > 2     = ["x"]
           | otherwise = []
    c2 i j | j > 5   = ["y", "a"]
           | otherwise = []
    c3 i j | j > 10  = ["z"]
           | otherwise = []
    c4 i j | j > 10 && i > 1 = ["z", "c", "hello"]
           | otherwise = []

3 个答案:

答案 0 :(得分:5)

您可以为此定义运算符:

infixl 1 *|

(*|) :: [a] -> Bool -> [a]
xs *| b | b = xs
xs *| b     = []

conditions i j = (["x"]             *| i > 2)
              ++ (["y", "a"]        *| j > 5)
              ++ (["z"]             *| j > 10)
              ++ (["z","c","hello"] *| j > 10 && i > 1)

它也可以将最后一行重写为

++ (["z","c","hello"] *| j > 10 *| i > 1)

如果出于某种原因需要这样做。

答案 1 :(得分:4)

这是你在找什么?

conditions i j = (if i > 2 then ["x"] else [])
                 ++ (if j > 5 then ["y","a"] else [])
                 ++ (if j > 10 then ["z"] else [])
                 ++ ...

答案 2 :(得分:2)

我的首选:

conditions i j = (guard (i>2)             >> ["x"]) ++
                 (guard (j>5)             >> ["y","a"]) ++
                 (guard (j > 10 && i > 1) >> ["z", "c", "hello"] )

列表理解滥用:

conditions i j = [ x | i>2 ,             x <- ["x"] ] ++
                 [ x | j>5 ,             x <- ["y","a"] ] ++
                 [ x | j > 10 && i > 1 , x <- ["z", "c", "hello"] ]

conditions i j = concat ( [ ["x"]               | i>2 ] ++
                          [ ["y","a"]           | j>5 ] ++
                          [ ["z", "c", "hello"] | j > 10 && i > 1 ] )