Michael Erik Florentin Nielsen wrote:

 | >   let x :: N Int
 | >       x = veryBigExpression
 | >  
 | >    in plus x x
 | > 
 | > Then "veryBigExpression" depending on an "Env" gets computed twice if you
 | > finally provide the "Env".
 | 
 | I do not see this as a problem. [...]
 | One could imagine that plus [...]
 | did not treat its arguments in the same way,
 | ie. it evaluates the two x'es in
 | different environments, [...].

Okay, if this happens a lot then you might not
gain so much from memoizing the functions.
But it still it hardly *hurts* (if used with
care, because of potential space problems).

 |   do x<-veryBigExpression
 |      plus (return x) (return x)
 | 
 | It is not that hard to read, I think.

You could even imagine a "sharing combinator":

  share :: N a -> (N a -> N b) -> N b
  share na f =
    do a <- na
       f (return a)

So the example would be:

  veryBigExpression `share` \x -> plus x x

This works fine for numeric computations, or
other kinds of computations where you don't
have recursion. If you have recursive expressions
involving "N a" then the sequentiality imposed
by the monadic view is too restrictive.

One can start using monadic fixpoint combinators
to overcome this, but that is really not
"not that hard to read" anymore (eufemistically).

So in the case of reader monads, memoizing is a nice
trick to avoid having to use monadic programming style.

I think the do-notation is fine when you have a monad
which is really "sequential". Otherwise, one should look
for other methods.

This implies a natural question: are there "functional"
programming styles for more commutative monads?
For example:

  - reader monads (we have seen the memoizing solution),

  - writer monads (where the monoid is commutative),

  - "distribution monads" (I recently came up with
    this name for a kind of reader monad which can split
    its environment up in two independent parts
    and distribute it over sub-computations) (for
    example for random numbers or unique identifiers)

Any thougths?

Regards,
Koen.

--
Koen Claessen         http://www.cs.chalmers.se/~koen     
phone:+46-31-772 5424      e-mail:[EMAIL PROTECTED]
-----------------------------------------------------
Chalmers University of Technology, Gothenburg, Sweden

Reply via email to