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
We can define functions with names so we can easily refer to them later. Named functions are defined within a module using the def keyword. Named functions are always defined in a module. To call named functions, we need to reference them using their module name.
To define an anonymous function in Elixir we need the fn and end keywords. Within these we can define any number of parameters and function bodies separated by -> . Let's look at a basic example: iex> sum = fn (a, b) -> a + b end iex> sum.(
Arity means how many input parameters Elixir function has. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric. In Elixir, function uniqueness is defined with: Module name.05-Jun-2020.
Syntax. The building blocks of an anonymous function are fn , -> , and end . When calling the anonymous function, we write the assigned name, followed by . , and then any of the function's parameters.
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")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With