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

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.