There is now a way to do this :). What used to be the Haskell Array
Preprocessor is not the Haskell STate Preprocessor (STPP) and it supports
now many things:
- sugared array reading/writing/updating
- sugared hash table reading/writing/updating
- monadic if
- monadic case
Get it from
Hello all. I was just thinking that there ought to be a better way to
write the following code. It seems to be a common case that within a 'do'
I bind a variable that I only intend to use once, in an if or case
statement. It occurred to me that there ought to be a better way to do
this. For
whatisit :: String - IO String
whatisit f = do
ifM doesDirectoryExist f
then return dir
else ifM doesFileExist f
then return file
else return nothing
Is there any way I could do something like this?
Not with the syntactic sugar of 'if'.
But you can
Not with the syntactic sugar of 'if'.
But you can write [warning: untested code ahead]
ifM :: IO Bool - IO a - IO a - IO a
ifM test yes no = do
b - test
if b then yes else no
There is a little trick that allows you to sort-of get the syntactic sugar. It goes
like this [warning:
Here's another way to sugar if-then-else that works like C's ?: and Lisp's cond:
import Monad (liftM3)
import Directory (doesFileExist, doesDirectoryExist)
infix 1 ?, ??
(?) :: Bool - a - a - a
(c ? t) e = if c then t else e
(??) :: (Monad m) = m Bool - m a - m a - m a
(??) = liftM3 (?)
main
G'day all.
On Thu, Feb 13, 2003 at 02:54:42PM -0500, David Roundy wrote:
That's pretty nice (although not quite as nice as it would be to be able to
use real ifs with no extra parentheses). Any idea how to do something like
this with a case?