Skip to content

Instantly share code, notes, and snippets.

@raichoo
Created September 30, 2016 16:53
Show Gist options
  • Save raichoo/c524860b3b920e541cc6aa3a2a893ffe to your computer and use it in GitHub Desktop.
Save raichoo/c524860b3b920e541cc6aa3a2a893ffe to your computer and use it in GitHub Desktop.
Haskell Example
module Assign where
import Data.IORef
mkSummer :: IO (Int -> Int -> IO Int)
mkSummer = do
ref <- newIORef 0
return $ \x y -> do
val <- readIORef ref
let ret = val + x + y
writeIORef ref ret
return ret
@raichoo
Copy link
Author

raichoo commented Oct 6, 2016

Here is a purer version of the idea using StateT (I'm mainly using the Transformer to print the intermediate results).

module Foo where

import Control.Monad (void)
import Control.Monad.Trans.State
import Control.Monad.IO.Class (liftIO)

sum' :: Monad m => Int -> Int -> StateT Int m Int
sum' x y = do
  c <- get

  let res = c + x + y

  put res

  return res

main :: IO ()
main = void $ flip runStateT 0 $ do
  sum' 5 5 >>= liftIO . print
  sum' 5 5 >>= liftIO . print

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment