Skip to content

Instantly share code, notes, and snippets.

@bergmark
Last active March 16, 2021 12:04
Show Gist options
  • Save bergmark/9ff3f3f7c2ed02d2abbf39a95faa51b7 to your computer and use it in GitHub Desktop.
Save bergmark/9ff3f3f7c2ed02d2abbf39a95faa51b7 to your computer and use it in GitHub Desktop.
Yes, haskell has for loops
module Main where
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.State
main :: IO ()
main = do
forLoop 0 (< 10) (+ 1)
print
forLoop :: i -> (i -> Bool) -> (i -> i) -> (i -> IO ()) -> IO ()
forLoop init pred change run =
void $ flip runStateT init $ iter pred change run
iter :: (i -> Bool) -> (i -> i) -> (i -> IO ()) -> StateT i IO ()
iter pred change run = do
i <- get
if pred i
then do
liftIO (run i)
modify change
iter pred change run
else pure ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment