User Tools

Site Tools


confusing:lyahpop

Confusing pop statement in LYAH

Nothing is perfect. Even though a tremendous effort must have been taken to create LYAH )1 I found it very confusing - for a long time. Since, I understand Haskell more and more I just realised that there is also code

  1. which does not really make sense
  2. hence, generates warnings
  3. it also generates compiler errors, because of incompatibilities with new packages philosophies
  4. can generate runtime errors if the code would be extendend

LYAH )1 is stating here:

import Control.Monad.State  
 
pop :: State Stack Int  
pop = State $ \(x:xs) -> (x,xs)  
 
push :: Int -> State Stack ()  
push a = State $ \xs -> ((),a:xs)  

pop is already a stateful computation and push takes an Int and returns a stateful computation. Now we can rewrite our previous example of pushing 3 onto the stack and then popping two numbers off like this:

import Control.Monad.State  
 
stackManip :: State Stack Int  
stackManip = do  
    push 3  
    a <- pop  
    pop
  1. The line a ← pop is “assigning” a state to a binding (“variable”) a but a will never be picked up, and the with just pop discards the result completely.
  2. Hence, it creates compiler warning:
    • app\Main.hs:28:5: warning: [-Wunused-matches]
          Defined but not used: `c'
         |
      mm |     c <- pop
         |     ^
      app\Main.hs:33:5: warning: [-Wunused-do-bind]
          A do-notation statement discarded a result of type `Int'
          Suppress this warning by saying `_ <- pop'
         |
      nn |     pop
         |     ^^^
      Linking .stack-work\...
  3. The new package philosophy renamed the data type State to StateT (The StateT monad transformer).
    • app\Main.hs:21:10: error:
          Not in scope: data constructor `S.State'
          Perhaps you meant one of these:
            `S.StateT' (imported from Control.Monad.State),
            variable `S.state' (imported from Control.Monad.State)
          Module `Control.Monad.State' does not export `State'.
         |
      21 | push a = S.State $ \xs -> ((),a:xs)
         |          
  4. If you use to much pops in stackManip then you get the following runtime error:
    • …-exe…: app\Main.hs:xx:yy-zz: Non-exhaustive patterns in lambda
      • which is this line pop = S.state $ \(x:xs) → (x,xs)

LYAH )1 Learn You a Haskell for Great Good!

This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
You could leave a comment if you were logged in.
confusing/lyahpop.txt · Last modified: by 127.0.0.1

Except where otherwise noted, content on this wiki is licensed under the following license: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki