Elixir 1.3
Chapter 1
Take the Red Pill
“The Elixir programming language wraps
functional programming with
immutable state and an
actor-based approach to concurrency in a tidy, modern syntax. And it runs on the industrial-strength, high-performance, distributed Erlang VM. ”
Programming Should Be About Transforming Data
When we code with objects, we’re thinking about state. In this world, the class is king and our goal is data hiding.
In the real world, we don’t want to
model abstract hierarchies.
We don’t want to hide data, we want to transform it.
Combine Transformations with Pipelines
Unix users are used to the philosophy of small, focused command-line tools that can be
combined in arbitrary ways.
Each tool takes an input, transforms it, and writes the result in a format that the next tool (or a human)
can use.
These small programs do one thing well,
which makes them easier to test.
Our first Elixir function
defmodule Parallel do
def pmap(collection, func) do
collection
|> Enum.map(&(Task.async(fn -> func.(&1) end)))
|> Enum.map(&Task.await/1)
end
end
It takes a collection and a function, and returns the list that results from applying that function to each element of the collection.
But…it runs a separate process to do the conversion of each element.
Functions Are Data Transformers
Elixir lets us solve the problem in the same way the
Unix shell does.
Smaller more focused functions that we string together.
We can also easily run these functions in parallel.
Bruce Tate: “Most programmers treat threads and processes as a necessary evil; Elixir developers feel they are an important simplification.”
iex—Interactive Elixir
$ iex
Erlang/OTP 18 [erts-7.2.1] [source] [64-bit] [smp:4:4] [async-threads:10]
[hipe] [kernel-poll:false] [dtrace]
Interactive Elixir (1.2.3) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> 3 + 4
7
iex(2)> String.reverse "madamimadam"
"madamimadam"
iex(3)> 5 *
...(3)> 6
30
iex(4)>
There are several ways of exiting from iex—none are tidy.
The easiest two are typing Ctrl-C twice or typing Ctrl-G followed by q and Return.
IEx Helpers - h
iex(1)> h
IEx.Helpers
Welcome to Interactive Elixir. You are currently seeing the documentation for
the module IEx.Helpers which provides many helpers to make Elixir's shell more
joyful to work with.
This message was triggered by invoking the helper h(), usually referred to as
h/0 (since it expects 0 arguments).
You can use the h function to invoke the documentation for any Elixir module or
function:
┃ h Enum
┃ h Enum.map
┃ h Enum.reverse/1
You can also use the i function to introspect any value you have in the shell:
┃ i "hello"
There are many other helpers available:
• b/1 - prints callbacks info and docs for a given module
• c/2 - compiles a file at the given path
• cd/1 - changes the current directory
• clear/0 - clears the screen
• flush/0 - flushes all messages sent to the shell
• h/0 - prints this help message
• h/1 - prints help for the given module, function or macro
• i/1 - prints information about the given data type
• import_file/1 - evaluates the given file in the shell's context
• l/1 - loads the given module's beam code
• ls/0 - lists the contents of the current directory
• ls/1 - lists the contents of the specified directory
• pid/3 — creates a PID with the 3 integer arguments passed
• pwd/0 — prints the current working directory
• r/1 — recompiles and reloads the given module's source file
• respawn/0 — respawns the current shell
• s/1 — prints spec information
• t/1 — prints type information
• v/0 — retrieves the last value from the history
• v/1 — retrieves the nth value from the history
Help for all of those functions can be consulted directly from the command line
using the h helper itself. Try:
┃ h(v/0)
To learn more about IEx as a whole, just type h(IEx).
h IO
iex(2)> h IO
IO
Functions handling IO.
Many functions in this module expect an IO device as an argument. An IO device
must be a pid or an atom representing a process. For convenience, Elixir
provides :stdio and :stderr as shortcuts to Erlang's :standard_io and
:standard_error.
The majority of the functions expect char data, i.e. strings or lists of
characters and strings. In case another type is given, functions will convert
to string via the String.Chars protocol (as shown in typespecs).
The functions starting with bin* expect iodata as an argument, i.e. binaries or
lists of bytes and binaries.
IO devices
An IO device may be an atom or a pid. In case it is an atom, the atom must be
the name of a registered process. In addition, Elixir provides two shorcuts:
• :stdio - a shortcut for :standard_io, which maps to the current
Process.group_leader/0 in Erlang
• :stderr - a shortcut for the named process :standard_error provided in
Erlang
IO devices maintain their position, that means subsequent calls to any reading
or writing functions will start from the place when the device was last
accessed. Position of files can be changed using the :file.position/2 function.
h IO.puts
iex(3)> h IO.puts
def puts(device \\ group_leader(), item)
Writes the argument to the device, similar to write/2, but adds a newline at
the end. The argument is expected to be a chardata.
i - another helper
iex(4)> i 123
Term
123
Data type
Integer
Reference modules
Integer
ex(5)> i "cat"
Term
"cat"
Data type
BitString
Byte size
3
Description
This is a string: a UTF-8 encoded binary. It's printed surrounded by
"double quotes" because all UTF-8 encoded codepoints in it are printable.
Raw representation
<<99, 97, 116>>
Reference modules
String, :binary
Displays information about a value.
Compile and Run Code
IO.puts "Hello, World!
Convention dictates the file extensions
.ex and .exs.
.ex are used for compiled code.
.exs used for scripts.
/intro/hello_world.exs
$ elixir hello.exs
Hello, World!
Run the elixir command on a file:
$ iex
iex> c "hello.exs"
Hello, World!
[]
iex>
or use iex.
The c helper compiled and executed the source file.
Think Different(ly)
- Object orientation is not the only way to design code.
- Functional programming need not be complex or mathematical.
- The foundations of programming are not assignments, if statements, and loops.
- Concurrency does not need locks, semaphores, monitors, and the like.
- Processes are not necessarily expensive resources.
- Metaprogramming is not just something tacked onto a language.
- Even if it is work, programming should be fun.
Thank you!
Programming Elixir 1.3 Chapter 01
By Dustin McCraw
Programming Elixir 1.3 Chapter 01
- 1,417