Question

Can you create a list of functions and then execute them sequentially, perhaps passing them into do notation?

I'm currently doing this by mapping over a list of data and am wondering if I can call somehow pass the result as a series of sequential calls?

Was it helpful?

Solution

Something like this?

sequence [putStrLn "Hello", putStrLn "World"]

OTHER TIPS

If these are functions, ie pure, then you can use ($) or "apply":

execute functions argument = map ($argument) functions
-- execute [id,(1+),(1-)] 12 => [12,13,-11]

There's no guarantee that this happens sequentially of course, but you'll get a list of the return values.

If these are actions, ie impure, then what you want is called sequence_:

sequence_ [putStr "Hello", putStr " world", putStrLn "!"]

sequence_ is pretty easy to write yourself:

sequence_ [] = return ()
sequence_ (action:actions) = action >> sequence_ actions

There is also a sequence (without the underscore) that runs a bunch of actions and returns their results:

main = do
  ss <- sequence [readFile "foo.txt", readFile "bar.txt", readFile "baz.txt"]
  -- or ss <- mapM readFile ["foo.txt", "bar.txt", "baz.txt"]

good answers so far, but if you also want each function to act not on the original data but on the result of the previous function, look at the foldding functions, such as foldl, foldl1, and foldr:

fns = [(1-), (+2), (abs), (+1)]
helperFunction a f = f a
test1 n = foldl helperFunction n fns

and you may need the monadic version, foldM and foldM_ :

import Control.Monad
import Data.Char

helperFunction a f = f a
prnt = \s-> do putStrLn s; return s
actions = [return, prnt, return.reverse, prnt, return.(map toUpper), prnt, return.reverse, prnt] 
test2 str = foldM_ helperFunction str actions 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top