开发者

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

Can you create a list of functions and the开发者_JS百科n 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?


Something like this?

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


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 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜