nibbleToString 函数中的异常非详尽模式

nibbleToString Exception non-exhaustive patterns in function

我是 Haskell 的新手,我尝试编写一个函数,该函数接受布尔值列表,然后将其转换为相应的整数列表,即 nibbleToString [True,False,False, True] 的计算结果应为 1001。我的代码如下所示:


nibbleToString :: [Bool] -> [Int]
nibbletoString [] = []
nibbleToString (x:xs)
    | x == True = [1] ++ nibbleToString xs
    | otherwise = [0] ++ nibbleToString xs

它编译,但是当我执行它时我得到

[1,0,0,1*** Exception: klausurprep.hs:(79,1)-(81,42): Non-exhaustive patterns in function nibbleToString

我也不知道为什么。在我的理解中,有三种可能的输入类别:空列表、以 true 开头的列表和以 false 开头的列表,我已经考虑了所有这三个,所以我不明白为什么我的模式不是详尽无遗的.预先感谢您的帮助!

nibbletoString 应该是 nibbleToString,

将单个值附加到列表[a] ++ as称为consing:a : as,你可以这样写

nibbleToString :: [Bool] -> [Int]
nibbleToString []         = []
nibbleToString (True :xs) = 1:nibbleToString xs
nibbleToString (False:xs) = 0:nibbleToString xs

整个定义可以写成nibbleToString = map fromBoolmap 将函数 fromBool 应用于列表的每个元素

-- map = fmap @[]
map :: (a -> b) -> ([a] -> [b])
map f []     = []
map f (a:as) = f a:map f as

-- fromBool = fromEnum @Bool
fromBool :: Bool -> Int
fromBool True  = 1
fromBool False = 0