Let's say I have a list of values to which I want to apply a sequence of operations until I get a final result:
[0, 1, 2]
firstOperation xs = map (+1) xs
secondOperation xs = filter even xs
thirdOperation xs = sum xs
Although I am sure there are开发者_高级运维 other better ways to handle this, the only one I currently know is to define a function that calls all these functions nested one inside another:
runAllOperations xs = thirdOperation (secondOperation (firstOperation xs))
but this is both ugly and raises the problem that if I have 10 operations, turns this bit of code into a maintanance nightmare.
What is the correct way of implementing something of the kind here? Keep in mind the example I gave above is just a oversimplification of what I am facing on my current project.
.
or $
are way more readable than (
and )
runAllOperations xs = thirdOperation $ secondOperation $ firstOperation xs
or
runAllOperations = thirdOperation . secondOperation . firstOperation
If you can make a list of all the operations, you can then fold the composition operator over that list:
foldr (.) id fns
Then you can apply the result of that to the initial values.
Though you might need to apply a final reduction step separately.
精彩评论