为什么foldr的这个case表达式不起作用?

时间:2017-11-30 12:38:34

标签: haskell case

以下功能应采用" 7-8-X"并转换为[7,8,10]

convertCharToInteger :: Char -> Integer
convertCharToInteger = (read::String->Integer) . (:[])

parseAsNumbers :: String -> [Integer]
parseAsNumbers xs = foldr (\x acc -> case x of '-' -> acc
                                           'X' -> 10:acc
                                            _  -> (convertCharToInteger x):acc
                      ) [] xs

它给了我以下错误

表达式上下文中的模式语法:

\x acc
    -> case x of {
      '-' -> acc
      'X' -> 10 : acc (...) } -> (convertCharToInteger x) : acc

2 个答案:

答案 0 :(得分:0)

您应该开始在新行上列出案例并将其对齐如下:

parseAsNumbers :: String -> [Integer]
parseAsNumbers xs = foldr (\x acc -> case x of
                                       '-' -> acc
                                       'X' -> 10:acc
                                       _   -> (convertCharToInteger x):acc
                      ) [] xs

答案 1 :(得分:0)

模式应该对齐,如下所示:

parseAsNumbers :: String -> [Integer]
parseAsNumbers xs = foldr (\x acc -> case x of '-' -> acc
                                               'X' -> 10:acc
                                               _   -> (convertCharToInteger x):acc) [] xs

此外,您可以使用read代替convertCharToInteger

parseAsNumbers :: String -> [Integer]
parseAsNumbers xs = foldr doit [] xs
    where
        doit = \x acc -> case x of
            '-' -> acc
            'X' -> (10:acc)
            _   -> (read [x]:acc)