Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
For loop
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===1990: Haskell=== {{Further|Haskell}} In Haskell98, the function ''mapM_'' maps a [[monad (functional programming)|monadic]] function over a list, as <syntaxhighlight lang="haskell"> mapM_ print [4, 3 .. 1] -- prints -- 4 -- 3 -- 2 -- 1 </syntaxhighlight> The function ''mapM'' collects each iteration result in a list: <syntaxhighlight lang="Haskell"> result_list <- mapM (\ indx -> do{ print indx; return (indx - 1) }) [1..4] -- prints -- 1 -- 2 -- 3 -- 4 -- result_list is [0,1,2,3,4] </syntaxhighlight> Haskell2010 adds functions ''forM_'' and ''forM'', which are equivalent to ''mapM_'' and ''mapM'', but with their arguments flipped: <syntaxhighlight lang="Haskell"> forM_ [0..3] $ \ indx -> do print indx -- prints -- 0 -- 1 -- 2 -- 3 result_list <- forM ['a'..'d'] $ \ indx -> do print indx return indx -- prints -- 'a' -- 'b' -- 'c' -- 'd' -- result_list is ['a','b','c','d'] </syntaxhighlight> When compiled with optimization, none of the expressions above will create lists. But, to save the space of the [1..5] list if optimization is turned off, a ''forLoop_'' function could be defined as <syntaxhighlight lang="Haskell"> import Control.Monad as M forLoop_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m () forLoop_ startIndx test next f = theLoop startIndx where theLoop indx = M.when (test indx) $ do f indx theLoop (next indx) </syntaxhighlight> and used as <syntaxhighlight lang="Haskell"> forLoopM_ (0::Int) (< len) (+1) $ \indx -> do -- statements </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)