State Monad, sequences of random numbers and monadic code

前端 未结 3 1392
礼貌的吻别
礼貌的吻别 2020-12-28 08:46

I\'m trying to grasp the State Monad and with this purpose I wanted to write a monadic code that would generate a sequence of random numbers using a Linear Congruential Gene

3条回答
  •  甜味超标
    2020-12-28 09:21

    First of all, your example is overly complicated because it doesn't need to store the val in the state monad; only the seed is the persistent state. Second, I think you will have better luck if instead of using the standard state monad, you re-implement all of the state monad and its operations yourself, with their types. I think you will learn more this way. Here are a couple of declarations to get you started:

    data MyState s a = MyState (s -> (s, b))
    
    get :: Mystate s s
    put :: s -> Mystate s ()
    

    Then you can write your own connectives:

    unit :: a -> Mystate s a
    bind :: Mystate s a -> (a -> Mystate s b) -> Mystate s b
    

    Finally

    data Seed = Seed Int
    nextVal :: Mystate Seed Bool
    

    As for your trouble desugaring, the do notation you are using is pretty sophisticated. But desugaring is a line-at-a-time mechanical procedure. As near as I can make out, your code should desugar like this (going back to your original types and code, which I disagree with):

     nextVal = get >>= \ Random seed val ->
                          let seed' = updateSeed seed
                              val'  = even seed'
                          in  put (Random seed' val') >>= \ _ -> return val'
    

    In order to make the nesting structure a bit clearer, I've taken major liberties with the indentation.

提交回复
热议问题