首页 > 解决方案 > 如果在 Haskell 中有多重条件吗?

问题描述

我试图嵌套检查两个以上条件的守卫,如下所示:

f :: Int -> Int
f i
   | bool1
       | bool2 = a
       | bool3 = a2
       | otherwise = a3
   | bool4
       | bool5 = a4
       | bool6 = a5
       | otherwise = a6
   | bool8
...
   | otherwise = an


这给了我一个解析错误。这样做的正确方法是
用 && 展平警卫或
实现如下功能:

multiIf :: [Bool] -> [a] -> a
multiIf (x:xs) (l:ls) = if x then l else multiIf xs ls
multiIf _ _ = undefined

还是有其他方法?

标签: if-statementhaskell

解决方案


不是直接的,但MultiWayIf 扩展可以为您提供非常相似的风格。

{-# LANGUAGE MultiWayIf #-}

f :: Int -> Int
f i
   | bool1
       = if | bool2 -> a
            | bool3 -> a2
            | otherwise -> a3
   | bool4
       = if | bool5 -> a4
            | bool6 -> a5
            | otherwise -> a6
   | bool8
...
   | otherwise = an

推荐阅读