O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Named Functions

Anonymous functions tend to be used for callback work—they are typically short and localized in their use. Named functions, however, are where the real work gets done.

Named functions can only exist inside Elixir modules. Here’s an example:

 defmodule​ AsciiDigit ​do
 def​ valid?(character) ​do
  character ​in​ ​?0​..​?9
 end
 end
 
 IO.inspect AsciiDigit.valid? ​?4​ ​# => true
 IO.inspect AsciiDigit.valid? ​?a​ ​# => false

To follow this code, you first have to know that the syntax ?x returns the integer character code for x (so ?0 is 48).

Our example defines a module called AsciiDigit containing a single function, valid?. This takes a character code and returns true if it is a digit from 0 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required