Can you turn a Haskell list into a series of do statements?

Can you create a list of functions and then execute them sequentially, possibly passing them to the notation?

I am currently doing this by matching a list of data, and I wonder if I can somehow pass the result as a sequence of consecutive calls?

+4
source share
3 answers

Something like that?

sequence [putStrLn "Hello", putStrLn "World"] 
+9
source

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

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

There is no guarantee that this will happen in sequence, but you will get a list of return values.

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

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

sequence_ pretty easy to write yourself:

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

There is also a sequence (without underscore) that launches 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"] 
+5
source

good answers, but if you also want each function to act not on the source data, but on the result of the previous function, look at the bending functions like foldl, foldl1 and foldr:

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

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

 import Control.Monad import Data.Char helperFunction af = fa 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 
+3
source

Source: https://habr.com/ru/post/1303713/


All Articles