[Haskell] return?

Graham Klyne GK at ninebynine.org
Fri Apr 30 11:45:44 EDT 2004


>Is this possible at all?

I don't think so, in the form that you suggest.

Ultimately, it all comes down to function applications, for which there is 
no such "bail out".  Rather, I think something like this is required:

   do
     { ...
     ; if cond then return 1
       else do
         (the rest)
     }

Here's an example from some real (tested) code:
[[
-- Open and read file, returning its handle and content, or Nothing
-- WARNING:  the handle must not be closed until input is fully evaluated
repOpenFile :: String -> RepStateIO (Maybe (Handle,String))
repOpenFile fnam =
     do  { (hnd,hop) <- lift $
             if null fnam then
                 return (stdin,True)
             else
             do  { o <- try (openFile fnam ReadMode)
                 ; case o of
                     Left  e -> return (stdin,False)
                     Right h -> return (h,True)
                 }
         ; hrd <- lift $ hIsReadable hnd
         ; res <- if hop && hrd then
             do  {
                 ; fc <- lift $ hGetContents hnd
                 ; return $ Just (hnd,fc)
                 }
             else
             do  { lift $ hClose hnd
                 ; repError ("Cannot read file: "++fnam) 3
                 ; return Nothing
                 }
         ; return res
         }
]]

#g
--

>Hi,
>While writing monad programs, I sometimes want to do a return as it is in
>imperative program. i.e.,
>do{return 1; return 2} is same as return 1
>
>This seems useful to me when I need to do something like
>do
>   mwhen cond $ return 1
>   ...... -- subsequent actions
>
>
>I know I can do
>if cond then return 1 else (
>   ...--subsequent actions
>   )
>
>
>  However, that syntax does not look very pleasant to me due to this extra
>indentation and the pair of parens.
>
>
>Is this possible at all?
>
>Ben.
>
>_______________________________________________
>Haskell mailing list
>Haskell at haskell.org
>http://www.haskell.org/mailman/listinfo/haskell

------------
Graham Klyne
For email:
http://www.ninebynine.org/#Contact



More information about the Haskell mailing list