Friday, December 8, 2017

Elixir: Anonymous Functions - A Taste of Functional Programming

An anonymous function is composed of an optional parameter list, a body enclosed by fn -> and end. It returns a function definition and the potential for the function to be executed. Quite simply the anonymous function can be assigned to a variable which then can be subsequently called.

Define an anonymous function:,
greet = fn ->
  IO.puts "Hello World"
Of course that does nothing unless we call it! We can do that by using this dot notation -
[function name].([optional parameters])
Like this:
Where the output is: Hello World

Anonymous functions with parameters

add = fn(num1, num2) ->
  num1 + num2

IO.puts add.(10, 15)
IO.puts add.(12, 15)
IO.puts add.(14, 19)

subtract = fn num1, num2 -> num1 - num2 end
IO.puts subtract.(15, 10)

I hope these examples ignite an interest for you to further learn functional programming using Elixir. Cheers!

Other posts in this series:
  • A Taste of Functional Programming
  • Anonymous functions
  • Pattern matching
  • Multi-bodied functions
  • Higher order functions
  • Side effects and state
  • Composition
  • Enumerables
  • Partial function applications
  • Recursion
  • Concurrency
  • Transitioning from OOP to functional

No comments:

Post a Comment