State vs compose - Haskell

Welcome to the Functional Programming Zulip Chat Archive. You can join the chat here.

Sridhar Ratnakumar

I build a list of "edit" functions to modify a graph datastructure. The functions list is evaluated using compose, which is defined as:

compose :: [a -> a] -> a -> a
compose = foldr (.) id

See full code here: https://github.com/srid/ka/blob/b24fc03dee53a91fd11122422405b3be3939eeb0/src/Ka/Graph.hs#L24-L48

As I was refactoring line 38-44, by injecting that anonymous function (\g -> ...), it occured to me that this whole thing looked similar to some well-known monad. Lo and hold - modify of Reader:

modify :: MonadState s m => (s -> s) -> m ()

So, my code can be rewritten to use State.

The question is: which version is more performant?

neuron is undergoing a heart surgery. Contribute to srid/ka development by creating an account on GitHub.
neuron is undergoing a heart surgery. Contribute to srid/ka development by creating an account on GitHub.
Sridhar Ratnakumar

fok it. State version is easier to read: https://github.com/srid/ka/commit/edd9ff9d6c485d88431064c38d52bbd5aae13109

neuron is undergoing a heart surgery. Contribute to srid/ka development by creating an account on GitHub.
Georgi Lyubenov // googleson78

well it's exactly a state monad, except everywhere you have () for your "result" parameter (so it'll be m () everywhere)

Georgi Lyubenov // googleson78

so it should be somewhat same performance? (very questionable claims :D )

Georgi Lyubenov // googleson78

actually state still internally does tupling+de-tupling, so maybe your original thing is faster in the end
it also doesn't have the cross-module specialisation issues that using mtl type classes has

TheMatten

I guess we would need to consult Core to know for sure

TheMatten

Because GHC could remove case of known constructor

TheMatten

(I mean, we're talking about compiler that can optimize out (un)boxing, which is very similar)

Georgi Lyubenov // googleson78

btw, for your a -> a usage, I think you can get away with only a Reader and local

Fintan Halpenny

Also fyi, I believe compose is foldMap Endo :eyes:

Georgi Lyubenov // googleson78

yeah but you need to unwrap it afterwards, and the noise becomes more than just foldr (.) id

Georgi Lyubenov // googleson78

I wish there was something like sum is to (+) for (.)

Georgi Lyubenov // googleson78

or we had something like ApplyingVia

Sridhar Ratnakumar

Georgi Lyubenov // googleson78 said:

btw, for your a -> a usage, I think you can get away with only a Reader and local

not sure how that would work