[prev in list] [next in list] [prev in thread] [next in thread] 

List:       haskell-cafe
Subject:    Re: [Haskell-cafe] Monads as control structures?
From:       Bulat Ziganshin <bulatz () HotPOP ! com>
Date:       2005-10-27 20:15:37
Message-ID: 31348997922.20051028001537 () HotPOP ! com
[Download RAW message or body]

Hello Creighton,

Thursday, October 27, 2005, 7:54:22 PM, you wrote:

CH> Haskell seems to me to be a very powerful language, and it
CH> looks like it should be possible to define control 
CH> structures such as for loops using monads.

it's my own lib:

-- |Conditional execution
whenM cond action = do
  allow <- cond
  when allow
    action

-- |Execute `action` only on (Just ...) value, returned by `x`
whenJustM x action  =  x >>= maybe (return Nothing) action

-- |Repeat forever
repeat_foreverM action = do
  action
  repeat_foreverM action

-- |Control structure like to `while` in Pascal
repeat_whileM inp cond out = do
  x <- inp
  if (cond x)
    then do out x
            repeat_whileM inp cond out
    else return x

-- |Control structure like to `repeat-until` in Pascal
repeat_untilM action = do
  done <- action
  when (not done) $ do
    repeat_untilM action

-- |Execute `action` on `x`, then on each element of list, returned by `action` and further recursively
recursiveM action x  =  action x  >>=  mapM_ (recursiveM action)

-- |Execute `action` recursively if `cond` is true and only on `x` otherwise
recursiveIfM cond action x  =  if cond  then recursiveM action x  else (action x >> return ())


i also like to use mapM to iterate over lists:

xs_processed <- (`mapM` xs) $ \x -> do
  -- some code using `x`
  return ...


-- 
Best regards,
 Bulat                            mailto:bulatz@HotPOP.com




[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic