[Haskell-beginners] do notation, pattern matching, if, & case
Brandon Allbery
allbery.b at gmail.com
Tue Aug 26 18:23:35 UTC 2014
On Tue, Aug 26, 2014 at 2:16 PM, Vale Cofer-Shabica <
vale.cofershabica at gmail.com> wrote:
> However, if I try to use f' or f'', I get parse errors. Three questions:
>
> * Is there a better way of doing this
> * Are stylistic changes to f really called for?
> * How can/ought I correct my syntax errors?
>
if and case are expressions. As such they are not part of the outer "do"'s
syntax; you would need a new "do" in each one. This will make more sense if
you study how "do" is converted to uses of the (>>) and (>>=) operators.
Additionally you can't just use "s <- getContents" like that, since (a) "s"
will go out of scope, abnd (b) with nothing following, it expands to a
syntax error ("getContents >>= \s ->" with nothing after the "->"). Since
if and case are expressions, you need to produce a result from them and
bind it at the top level. So you really want something like:
f' :: String -> IO ()
f' file = do
s <- if file == "-"
then getContents
else readFile file
putStrLn s
--
brandon s allbery kf8nh sine nomine associates
allbery.b at gmail.com ballbery at sinenomine.net
unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20140826/4b0dba3e/attachment.html>
More information about the Beginners
mailing list