M Taylor
M Taylor

Reputation: 23

In elm, how can I pipe a value to a function as an argument other than the last one?

I'm new to elm and to be honest struggling a bit to get my head around certain concepts right now. I'm not sure how clear my question is but this is what I'm trying to do.

for example:

aFunction value1 value2

is equivalent to:

value2
  |> aFunction value1

but what if I want to pass value1 to aFunction through a pipe instead of value2?

at the moment I'm using something like this:

value1
  |> (\x y -> aFunction y x) value2

However, it strikes me as a bit of a kludge, to be honest. Is there a more elegant way to do this?

What I'm trying to code in practice is part of quite a long chain of pipes which would be impractical (or at least unreadable) to do using an expression with lots of parentheses.

Upvotes: 2

Views: 398

Answers (2)

M Taylor
M Taylor

Reputation: 23

As per @chepner's answer, flip seems to be the best way to do this for functions with 2 arguments.

Given that there doesn't seem to be any built in solution to the wider question of how to do this for functions having more than 2 arguments, I came up with the following.

I'm really not sure if this is likely to be particularly useful in real life, but it was (at least) an interesting exercise for me as I'm really still learning fairly basic stuff:

module RotArgs exposing (..)

rot3ArgsL1 func = \y z x -> func x y z

rot3ArgsL2 func = \z x y -> func x y z

rot4ArgsL1 func = \x y z w -> func w x y z

rot4ArgsL2 func = \y z w x -> func w x y z

rot4ArgsL3 func = \z w x y -> func w x y z

So, for example rot3ArgsL1 takes a 3-argument function and returns a version of that function in which the expected order of arguments has been rotated 1 place to the left... and so forth.

It would enable things like:

import RotArgs exposing (..)

someFunction one two three =
  ...whatever

...

one
  |> (rot3ArgsL1 someFunction) two three

Obviously RotArgs could easily be extemded to functions of more than 4 arguments, though that seems likely to be increasingly less useful the more arguments are added.

Upvotes: 0

chepner
chepner

Reputation: 530940

Use the flip function (which is just the function you are defining in-line with the lambda expression):

value1 |> (flip aFunction) value2

Upvotes: 5

Related Questions