Skip to content

Instantly share code, notes, and snippets.

@hasufell hasufell/For.hs
Last active Sep 16, 2017

Embed
What would you like to do?
For loop in haskell
module For where
import Control.Monad
import Data.IORef
for :: IO a -- ^ init
-> (a -> IO Bool) -- ^ cond
-> (a -> IO ()) -- ^ incr
-> (a -> IO ()) -- ^ body
-> IO ()
for init cond incr bod = do
v <- init
go v
where
go v = do
c <- cond v
when c $ do
bod v
incr v
go v
doSomething :: IO ()
doSomething = do
for (newIORef (0, 1.2)) cond incr body
where
cond rvar = do
(x, y) <- readIORef rvar
return (x < 10 || y < 10)
incr rvar = modifyIORef rvar (\(x, y) -> (x+1, y+1.0))
body rvar = do
(x, y) <- readIORef rvar
print x
print y
@mstksg

This comment has been minimized.

Copy link

commented Nov 4, 2016

The more faithful/general case w/o abstraction:

for
    :: IORef a     -- ^ variable
    -> (IORef a -> IO ())   -- ^ init
    -> (IORef a -> IO Bool)  -- ^ cond
    -> (IORef a -> IO ())    -- ^ incr
    -> (IORef a -> IO ())    -- ^ body
    -> IO ()
for r init cond incr bod = do
    x0 <- init r
    go
  where
    go :: IO ()
    go = do
      c <- cond r
      when c $ do
        bod r
        incr r
        go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.