an erlang monad?

Matthias Kretschmer <>
Wed Mar 2 18:25:47 CET 2005


On Wed, 2 Mar 2005 16:28:39 +0100
"Ulf Wiger \(AL/EAB\)" <> wrote:

> 
> I have had reason to do some rather complex code using
> a 'dict' dictionary. I find myself constantly wishing
> for a library function (and eventually writing it 
> myself) that does the following:
> 
> with(Dict, Actions) ->
>     lists:foldl(fun(F,D) ->
>                         F(D)
>                 end, Dict, Actions).
> 
> That is, fold over a list of functions that update
> the dictionary. This, I believe, essentially amounts
> to a monad in other languages. ;-) Even if this is 
> just me misunderstanding monads (like everyone else),
> I find the function very useful.

This is something I use monads for, too. Hiding some sort of state or other information (serialization of operation or doing i/o is not that much of a concern using Erlang :-)). I wrote a little parse_transform'er to make the notation easier:

monad(MT,
  Action0,
  Action1,
  1 = mreturn(1),
  Action2,
  X = Action3,
  Action4,
  Action5(X)).

this would be roughly like (assuming MT.>>= is an infix operation):

Action0 MT.>>= fun (_) ->
Action1 MT.>>= fun (_) ->
MT.return(1) MT.>>= fun (1) ->
Action2 MT.>>= fun (_) ->
Action3 MT.>>= fun (X) ->
Action4 MT.>>= fun (_) ->
Action5(X) end end end end end

trying to resemble basically Haskell's do-notation -- except that instead of "X <- Action" "X = Action" (the MT is the monad type specification -- basically a tuple containing the "bind"/">>=", "return", etc. functions).

Your with/2 function may be easily translated to this notation. I like this notation, because it may be easily used for other types of monads, too, not only the basic state carrying monad and it is possible to build a set of basic combinators that may be used with any monad type. Like backtracking parsers or other stuff.

This way you may even drop the fun (D) -> ... end and just write the
expressions, using appropriate monad values for reading and writing the
state (e.g. wrapping the basic dictionary operations).

I think a really nice do-notation or something like that would be very nice to have in Erlang. I am always missing it (though I am currently quited happy with my transformation-hack).

--
cheers
Matthias Kretschmer



More information about the erlang-questions mailing list