Advertisement
Guest User

Imperative Programming in Haskell

a guest
May 29th, 2021
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-
  2.  
  3. ...but what if we need state?
  4. How would we write this imperative pseudocode in Haskell without the IO monad or any other monad?
  5.  
  6. x = 1
  7. y = 2
  8. x = x + y        comment: x == 3
  9. y = x * y        comment: y == 3 * 2 = 6
  10. result = x + y   comment: 3 + 6 = 9
  11.  
  12. -}
  13.  
  14. type LineLabel = Int
  15. type Program t = LineLabel -> t
  16.  
  17. p :: Program (Int -> Int -> Int -> Int)
  18. p 0  x y r  =  p 1  1 y r       -- x = 1
  19. p 1  x y r  =  p 2  x 2 r       -- y = 2
  20. p 2  x y r  =  p 3  (x + y) y r -- x = x + y
  21. p 3  x y r  =  p 4  x (x * y) r -- y = x * y
  22. p 4  x y r  =  p 5  x y (x + y) -- r = x + y
  23. p 5  x y r  =  r
  24.  
  25. program :: Int
  26. program = p 0 0 0 0
  27.  
  28. -- program == 9
  29.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement