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

David McBride toad3k at gmail.com
Wed Jul 11 17:30:51 UTC 2018


1)  Not entirely sure what you mean.  The expression is parsed as (read
numberString) : xs, which means that the result number is prepended to the
front of the list.

2) Because [(x,"")] does not match [(1.0," wawawawa")].  An empty string
does not match a string with characters in it.

On Wed, Jul 11, 2018 at 1:24 PM, Olumide <50295 at web.de> wrote:

> 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
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20180711/0353776d/attachment.html>


More information about the Beginners mailing list