user1311390
user1311390

Reputation:

Implementing Reduce as a Monadic Map in via org.clojure/algo.monads

Context

I'm currently reading about Clojure's implementation of monads: org.clojure/algo.monads

Intuitively, reduce looks like a state-m applied to a map. Basically, there's the "state" which is the value so far.

Now, I can't make this work in the "standard way because:"

(domonad state-m
   [ ... I can only stuff a constant number of things here ...
     ... but I need to stuff here a list whose size is only known at run time ... ]
    ..)

Question

Is there some way to implement reduce as a monad using state-m?

I know I would never use this in practice, this is purely for enlightenment + better understanding how things fit together.

Thanks!

Upvotes: 1

Views: 121

Answers (2)

mikera
mikera

Reputation: 106401

The state monad itself doesn't have any concept of iteration over lists. So you can't do this directly using the state monad.

You could use a state monad in a loop to emulate reduce - but the loop itself would be what is providing the reduce-like behaviour, the state monad itself wouldn't really be contributing anything.

Upvotes: 0

Ankur
Ankur

Reputation: 33657

I don't think what you are asking for is possible using domand macro (without runtime code generation and evaling it). One option would be to use m-bind and m-result functions of the state monad directly to get the desired behavior.

Upvotes: 1

Related Questions