Elixir Course Online | Prograils - Software Development Company
Anonymous functions exercises
Exercises
Create and execute an anonymous functions (both with standard and short
&
notation) which calculates square area of:- square,
- rectangle,
- circle (assume that Pi is 3.14).
Rewrite given anonymous functions with
&
notation:Enum.find([2, 3, 4], fn x -> rem(x, 2) == 1 end)
Enum.flat_map_reduce(1..5, 0, fn x, acc -> {[[x]], acc + x} end)
Create an anonymous function which meets the criteria:
- when you pass
first_name
it will print "Hello User" (where "User" isfirst_name
in this case), - when you pass
last_name
it will print "Hello Example" (where "Example" islast_name
in this case), - when you pass
first_name
andlast_name
it will print "Hello User Example" (where "User" isfirst_name
and "Example" islast_name
in this case), - when you don't pass any arguments it should print "Who you are?".
- you should not use any control flow mechanisms,
- use different function implementations depending on given arguments,
- use pattern matching to execute proper function implementation based on different arguments.
- when you pass
Create an anonymous function which takes two arguments: number and an anonymous function. Your function should execute anonymous function (passed as a second argument) with a number (passed as a first argument). Try it out to perform following operations:
- multiplying by 10,
- dividing by 10,
- add 10 to given number,
- subtract 10 from given number.
Create an anonymous function which takes a number as an argument and returns another function. Execute nested function with another number. Sum of these two numbers should be returned as a result, for example:
iex> sum.(5).(6) 11
Create an anonymous function which performs the division of numbers. Use guard clause not to allow non-numeric arguments and zero as a second argument (in both cases provide feedback as a returned value).