[Haskell] Mixing monadic and non-monadic functions

Ben Rudiak-Gould Benjamin.Rudiak-Gould at cl.cam.ac.uk
Wed Sep 14 10:32:27 EDT 2005


Frederik Eaton wrote:
> I want the type system to be able to do "automatic lifting" of monads,
> i.e., since [] is a monad, I should be able to write the following:
> 
> [1,2]+[3,4]
> 
> and have it interpreted as "do {a<-[1,2]; b<-[3,4]; return (a+b)}".

The main problem is ambiguity: [[1]]++[[2]] could be [[1],[2]] or [[1,2]], 
for example. If your proposal resolves this ambiguity in favor of one result 
or the other, then I'm opposed to it -- it's far too easy in practice to 
write code like this, expecting it to be lifted, and failing to notice that 
it also has an interpretation without lifting (or the other way around). 
This is the Perl FWIM disease[1] -- not that I dislike Perl, but people are 
quite rightly leery about bringing this sort of thing into Haskell.

I have another proposal, though. Introduce a new keyword, which I'll call 
"borrow" (the opposite of "return"), that behaves like a function of type 
(Monad m) => m a -> a inside of do statements. More precisely, a do 
expression of the form

     do { ... ; ... borrow E ... ; ... }

is transformed into

     do { ... ; x <- E ; ... x ... ; ... }

where x is a fresh variable. If more than one borrow form appears in the 
same do statement, they are pulled out from left to right, which matches the 
convention already used in liftM2, ap, mapM, etc.

Pros:

     + Pure sugar; no tricky interactions with the type system.

     + Nice symmetry between putting a value in a monad and taking it out.

     + Potentially helpful for beginners who ask "how do I get a String
       from an IO String?"

Cons:

     - Needs a new keyword.

     - Pretends to be an expression but really isn't; perhaps
       distinctive syntax would be better. (Inline "<-"?)

     - Depends on enclosing do keyword: in particular, do { stmt } would
       no longer be equivalent to stmt, if stmt contains "borrow".
       Potential confusion.

     - Potentially misleading for beginners (but then so is do notation,
       and the keyword "class", and n+k patterns, and so on...)

-- Ben

[1] http://www.dcs.gla.ac.uk/~partain/haskerl/partain-1.html


More information about the Haskell mailing list