fadedbee
fadedbee

Reputation: 44715

Is it better to use the State monad, or to pass state recursively?

I'm just learning Haskell, and trying to figure out the most idiomatic way to implement a line of sight algorithm.

The demo code I found uses the state monad, but it seem simpler to me (I'm just a beginner) to pass state recursively. What am I missing here? Are there performance problems?

Find code at: http://www.finalcog.com/bresenham-algorithm-idiomatic-haskell

Thanks,

Chris.

Upvotes: 9

Views: 1391

Answers (3)

ChrisBlom
ChrisBlom

Reputation: 1281

An advantage of using a monad to pass on state rather than passing on state explicitly, is that there are many useful combinators defined for monads that you can use.

Upvotes: 3

Don Stewart
Don Stewart

Reputation: 137947

For larger programs, it is better to hide the state passing plumbing in the monad. There is less risk of error then.

Upvotes: 11

Macke
Macke

Reputation: 25680

It can become a bit verbose to pass state everywhere. Also, the state monad is well known by most haskell coders so they'll know what you're doing. If you hand-roll your own, outside a monad, it can be tricky to discern what your code does.

I find the state monad neat for encapsulating state changes, it's pretty obvious what part of your code is stateful (i.e. alters or depends on state) w.r.t. the rest of the pure stuff.

Upvotes: 12

Related Questions