Given a list of functions that transform a value, what is the most idiomatic way to apply them? Example:
let
transformations = [ String.replace "dogs" "cats"
, String.replace "bark" "purr"
]
str = "dogs are the best, they bark"
in
foldl (\t acc -> t acc) str transformations
I don't like the (\t acc -> t acc)
which seems redundant. But I couldn't come up with another way of writing the last line.
Of course in this simple example I could pull out the String.replace
into a function transform (s, r) = String.replace s r
. But in my use case the functions are arbitrary. Also I think I can learn something about the language that way :-)
The way you did it is idiomatic as the lambda is clear and Elm encourages clarity.
You could have used List.foldl (<|) str transformations
instead of the lambda but that is more cryptic for people that are not used to the reverse pipe being used as a function.
One other way to do it is:
applyAll : List (a -> a) -> a -> a
applyAll funcs start =
List.foldl (<|) start funcs
let
transformations = [ String.replace "dogs" "cats"
, String.replace "bark" "purr"
]
str = "dogs are the best, they bark"
in
applyAll transformations str