Is it possible to nest guards in Haskell?

前端 未结 8 932
野的像风
野的像风 2020-12-10 16:52

Haskell newbie here, trying to write code to parse math expressions. Code:

isDigit :: Char -> Bool
isDigit c = c >= \'0\' && c <= \'9\'

pars         


        
8条回答
  •  南笙
    南笙 (楼主)
    2020-12-10 17:17

    No, it's not possible. Why not just write it linearly as

    isDigit :: Char -> Bool
    isDigit c = c >= '0' && c <= '9'
    
    parseNumber :: String -> Maybe (String, String)
    parseNumber [] = Just ("", "")
    parseNumber (h:ls)
        -- Digit found
        | isDigit h && p == Nothing = Just([h], ls)
        -- Ends in a digit
        | isDigit h = Just (h:fst d, snd d)
        -- Ends in a point
        | h == '.' && p == Nothing = Nothing
        -- We don't want multiple dots
        | h == '.' && not ('.' `elem` (snd d)) = Just (h:(fst d), snd d)
        -- Not a number, stop looking!
        | otherwise = Nothing
        where
            p = parseNumber ls
            Just d = parseNumber ls -- Float version of p. Not used if p is Nothing
    
    main = print $ parseNumber "123.0 + 2"
    

    If your guards become too involved it's probably a sign that you need to extract a function.

提交回复
热议问题