Is it possible to nest guards in Haskell?

前端 未结 8 930
野的像风
野的像风 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:04

    Put them in separated functions.

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

    Have to admit I did not tested this code.

提交回复
热议问题