Proposal: Allow ampersand expression functions which do not use all arguments

159 views
Skip to first unread message

Julian Haeger

unread,
Jan 8, 2016, 6:02:49 AM1/8/16
to elixir-lang-core
Background
I had a situation this morning where I wanted to pass a function into a reduce which only made use of the accumulator, ie the 2nd argument. Initially I wrote it using the `fn` syntax, ie:
1..n |> Enum.reduce(a, fn (_ , acc) -> do_stuff(acc) end)

however I wanted to be able to be able to use an ampersand expression function (is there a proper name for this?) like this:
1..n |> Enum.reduce(a, &do_stuff(&2))

however, the compiler told me:
capture &2 cannot be defined without &1

Proposal
Would it make sense for the compiler to treat all unused &n (up to the maximum which is defined) as being _ arguments?
for example:
&(&3 +2)

would expand to:
fn(_,_,x) -> x+2 end


Alexei Sholik

unread,
Jan 8, 2016, 6:25:45 AM1/8/16
to elixir-lang-core
The ampersand syntax has been discussed extensively in the past. The general agreement there is that it's better for it to remain simple and uniform. If you need an anonymous function that takes no arguments or one that ignores some of its arguments, using `fn` is the right call.

As for your original problem, you could solve it as follows:

Stream.iterate(a, &do_stuff/1) |> Enum.take(n)

--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/588b7661-d71f-46da-ac8c-a3a9acf2543b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Julian Haeger

unread,
Jan 8, 2016, 10:13:42 AM1/8/16
to elixir-lang-core
I knew there must be a function for that use case! I was sniffing around Stream, but missed iterate.
Reply all
Reply to author
Forward
0 new messages