Skip to main content

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"
end
Of course that does nothing unless we call it! We can do that by using this dot notation -
[function name].([optional parameters])
Like this:
greet.()
Where the output is: Hello World

Anonymous functions with parameters

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

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)
Output:
25
27
33
5

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

Comments

Popular posts from this blog

Setting up Sinatra and DataMapper on Windows

I use a MacBook Pro for work and pleasure on a day-to-day basis. Recently, I was asked to teach web students at a local high school. These students know html/graphics/flash/etc. The advanced students were ready for some server-side programming and database integration. I wanted the students to be able to get up and going quickly (for motivation reasons) and to create useful apps (using a database). I felt Sinatra to be a great fit for this. I created a Sinatra app for my uncle and his business. It was a joy to work with it and I was able to deploy quickly using Heroku . My experience of using Sinatra on my Mac was straightforward. Like most things using Ruby and Mac: it just worked. However, I found out the students at the high school use MS Windows. Fortunately, I have a Windows XP virtual machine running in VMWare so I could prepare that way. I used to teach computer science and web development at Spokane Community College and am aware of teaching Ruby in a Windows lab environm

AngularJS 101: A Beginner's Tutorial

Below is the PDF article I submitted to Software Developer's Journal  for their series they did on AngularJS. It was published in two of their issues: Nov. 15th 2013 -  AngularJS, Java and Drupal Tips & Tricks and Nov. 7th 2013 -  AngularJS Starter Kit . It's behind a paywall and thus hidden from most of the world. That sucks... which is why I'm posting my article here for all to see. Enjoy! AngularJS 101: A Beginner's Tutorial Github code for application built in the tutorial

PHP and Laravel Development: A 17-part video series

 Enjoy!