Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir : Writing Parameterized Function using & Notation

Tags:

elixir

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
like image 984
Wand Maker Avatar asked Jul 20 '15 18:07

Wand Maker


People also ask

How do you write functions in Elixir?

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.

What is FN in Elixir?

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.(

What is arity in Elixir?

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.

How do you call anonymous using Elixir?

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.


2 Answers

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")
like image 96
Patrick Oscity Avatar answered Oct 08 '22 08:10

Patrick Oscity


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
like image 45
Gazler Avatar answered Oct 08 '22 07:10

Gazler