Answers for "haskell for loop"

0

haskell for loop

{- Simple loop -}
repeatNTimes 0 _ = return ()
repeatNTimes n action =
 do
  action
  repeatNTimes (n-1) action

main = repeatNTimes 10 (putStrLn "a string")

-- naive recursion
loop :: Int -> Int
loop n = loop' n 0
  where loop' 0 a = a
        loop' n a = loop' (n - 1) (1 - a)

-- restate recursion
loop :: Int -> Int
loop n = foldr (\a _ -> 1 - a) 0 [0..n]

-- using `Stete`
import Control.Monad
import Control.Monad.State

loop :: Int -> Int
loop n = execState (forM_ [0..n] 
                      (\_ -> modify (\a -> 1 - a))) 0
Posted by: Guest on June-12-2021

Browse Popular Code Answers by Language