[Haskell-beginners] Two small questions from the section "Making a safe RPN calculator" in LYAH

Olumide 50295 at web.de
Wed Jul 11 17:24:19 UTC 2018


Dear List,

Question 1:
In the section "Making a safe RPN calculator" of LYAH (Chapter 14 -- 
http://learnyouahaskell.com/for-a-few-monads-more#useful-monadic-functions) 
there is an expression: read numberString:xs, take from the last line of 
the function

     foldingFunction :: [Double] -> String -> [Double]
     foldingFunction (x:y:ys) "*" = (x * y):ys
     foldingFunction (x:y:ys) "+" = (x + y):ys
     foldingFunction (x:y:ys) "-" = (y - x):ys
     foldingFunction xs numberString = read numberString:xs

My first question is why is the read function called before the cons 
operator?

Question 2:
The same section of the book also introduces the reads function which is 
used to implement the readMaybe function and a refactored foldingFunction

     readMaybe :: (Read a) => String -> Maybe a
     readMaybe st = case reads st of [(x,"")] -> Just x
                                     _ -> Nothing

     foldingFunction :: [Double] -> String -> Maybe [Double]
     foldingFunction (x:y:ys) "*" = return ((x * y):ys)
     foldingFunction (x:y:ys) "+" = return ((x + y):ys)
     foldingFunction (x:y:ys) "-" = return ((y - x):ys)
     foldingFunction xs numberString = liftM (:xs) (readMaybe 
numberString)

I'd like to know why the foldingFunction returns Nothing in the 
following example:

ghci> foldingFunction [] "1 wawawawa"
Nothing

Considering that reads "1 wawawawa" does not return Nothing, as follows

ghci> reads "1 wawawawa" :: [(Double,String)]
[(1.0," wawawawa")]

Regards,

- Olumide



More information about the Beginners mailing list