简体   繁体   中英

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM