开发者

The reason for MonadState get and put?

开发者 https://www.devze.com 2022-12-25 08:55 出处:网络
I\'m reading the Monads chapter in Real World Haskell (chapter 14). A function is defined as follows: type RandomState a = State StdGen a

I'm reading the Monads chapter in Real World Haskell (chapter 14). A function is defined as follows:

type RandomState a = State StdGen a
getRandom :: Random a => RandomState a
getRandom =
    get >>= \gen ->
    let (val, gen')= random gen in
    put gen' >>
    return val

I don't really understand the purpose of the get and put functions here. I rewrote the function as following which seems to do the same th开发者_开发知识库ing and is more concise:

getRandom2 :: Random a => RandomState a 
getRandom2= State $ \ s -> random s

So my question is: What is the purpose of get and put in general?


It's a bit of a coincidence that random happens to have exactly the same type signature/usage pattern as the inner function of the State monad (and indeed in this case you could be even more concise, if perhaps more confusing, with getRandom2 = State random).

However, more generally that won't apply, and then get and put are convenient plumbing pieces whose meaning is perhaps clearer than writing the inner function directly. They also help to abstract from the precise representation used by State - they are actually class members of the more general class MonadState, so you can write more polymorphic code by using them.

0

精彩评论

暂无评论...
验证码 换一张
取 消