5
votes

Is it possible to write parameterized function using & notation?

Here is an example of parameterized function from Programming Elixir book of Dave Thomas

title = fn (title) -> ( fn (name) -> title <> " "  <> name end ) end

mrs = title.("Mrs.")
IO.puts mrs.("Rose")

Output of above program is:

Mrs. Rose
[Finished in 0.6s]

Can title be written using & notation? Example of & notation is given below

iex> square = &(&1 * &1)
#Function<6.17052888 in :erl_eval.expr/5>

iex> square.(8)
64
2

2 Answers

9
votes

As @Gazler correctly suggested this is not possible due to syntax limitations, but you can achieve a similar result with partial application. The difference here is that the title function will return a result directly, instead of returning a function. The mrs function can then do a partial application by "prefilling" the first argument.

title = &(&1 <> " "  <> &2)
mrs = &title.("Mrs.", &1)
IO.puts mrs.("Rose")
6
votes

This will not be possible. Attempting to use the capture(&) function syntax in a function declared with the capture syntax will raise a CompileError

iex(1)> &(&(&1))      
** (CompileError) iex:2: nested captures via & are not allowed: &&1
    (elixir) src/elixir_fn.erl:108: :elixir_fn.do_capture/4
    (elixir) src/elixir_exp.erl:229: :elixir_exp.expand/2
    (elixir) src/elixir_exp.erl:10: :elixir_exp.expand/2