focus v0.2.3 Lens
Lenses combine getters and setters for keys in data structures.
Lenses should match/operate over a single value in a data structure, e.g. a key in a map/struct.
Summary
Functions
A lens that focuses on an index in a list
Define a lens to Focus on a part of a data structure
Automatically generate the valid lenses for the supplied map-like data structure
Get a piece of a data structure that a lens Focuses on; returns {:ok, data} | {:error, :bad_lens_path}
Macros
Define a struct and derive lenses for the struct’s keys as functions in the module.
Example
Given the following module
Types
Functions
A lens that focuses on an index in a list.
Examples
iex> first_elem = Lens.idx(0)
iex> first_elem |> Focus.view([1,2,3,4,5])
1
iex> bad_index = Lens.idx(10)
iex> bad_index |> Focus.view([1,2,3])
nil
Define a lens to Focus on a part of a data structure.
Examples
iex> person = %{name: "Homer"}
iex> name_lens = Lens.make_lens(:name)
iex> name_lens |> Focus.view(person)
"Homer"
iex> name_lens |> Focus.set(person, "Bart")
%{name: "Bart"}
make_lenses(Focus.Types.traversable) :: %{optional(atom) => Lens.t, optional(String.t) => Lens.t}
Automatically generate the valid lenses for the supplied map-like data structure.
Examples
iex> lisa = %{name: "Lisa", pets: %{cat: "Snowball"}}
iex> lisa_lenses = Lens.make_lenses(lisa)
iex> lisa_lenses.name
...> |> Focus.view(lisa)
"Lisa"
iex> pet_lenses = Lens.make_lenses(lisa.pets)
iex> lisa_lenses.pets
...> ~> pet_lenses.cat
...> |> Focus.set(lisa, "Snowball II")
%{name: "Lisa", pets: %{cat: "Snowball II"}}
safe_view(Lens.t, Focus.Types.traversable) :: {:error, :bad_arg} | {:ok, any}
Get a piece of a data structure that a lens Focuses on; returns {:ok, data} | {:error, :bad_lens_path}
Examples
iex> marge = %{name: "Marge", address: %{street: "123 Fake St.", city: "Springfield"}}
iex> name_lens = Lens.make_lens(:name)
iex> Lens.safe_view(name_lens, marge)
{:ok, "Marge"}
Macros
Define a struct and derive lenses for the struct’s keys as functions in the module.
Example
Given the following module:
defmodule PersonExample do
import Lens
deflenses name: nil, age: nil
end
iex> function_exported?(PersonExample, :age_lens, 0)
true
iex> function_exported?(PersonExample, :name_lens, 0)
true
iex> bart = %PersonExample{name: "Bart", age: 10}
iex> require IEx; IEx.pry
iex> PersonExample.name_lens |> Focus.view(bart)
"Bart"
end