Piping a value throught a list of functions of unknown length

I would like to be able to pipe a value through a list of functions of unknown length:

``````lst = [\x ->x + 1, \x -> x + 2]
someFunc 2 lst
``````

would give 5

This works

https://ellie-app.com/3FjhGztpXmqa1

but I can’t help wondering if there’s a “neater” way? I wonder if I knew more about applicative functors I might be able to see a better way?

thoughts on how to do this in a neater way would be appreciated1

thanks

``````pipeThroughListOfFunctions : value -> List (value -> value) -> value
pipeThroughListOfFunctions value list =
case list of
[] ->
value

[ fn ] ->
fn value

h :: t ->
pipeThroughListOfFunctions (h value) t
``````

You can do `List.foldl (<|) 2 lst`.

This is equivalent to the `pipeThroughListOfFunctions` you wrote, since you can think of folds as an abstraction over recursion and the `<|` operator simply expresses function application.

6 Likes

Thanks very much @gameplan - that’s exactly the elegant kind of solution I thought would be possible
This functional programming is really elegant - mine looks like Scheme, yours looks much nicer!
again, thanks.

An alternative would be to fold the list with the `compose` operator (`>>` or `<<`). This way the result is a new function that is the sequential combination of all in the list.

``````lst =
[ \x -> x + 1, \x -> x * 2 ]

composedFunction =
List.foldl (<<) identity lst

composedFunction 2
``````

This is an alternative to the approach which is applying the value directly with the pipe operator (`|>`). It can make sense if several lists will be composed, or passed around. It could also be more clear with good naming (What will happen if all the functions are composed?). Otherwise @gampleman mentioned the most concise solution for this problem. Perfectly fine.

2 Likes

Ah yes - thanks @andys8 - I’ll work piping vs composing…

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.