Lonely v0.3.0 Lonely.Option View Source
Handles any value that could be nil as well.
Some functions result in either the value or just nil. For these ocasions
you can either transform it to a result with Lonely.Result.wrap/1 or
use this module.
iex> import Lonely.Option
...> [1, 2, 3]
...> |> Enum.find(fn x -> x == 2 end)
...> |> map(fn x -> x * 10 end)
20
iex> import Lonely.Option
...> [1, 2, 3]
...> |> Enum.find(fn x -> x == 10 end)
...> |> map(fn x -> x * 10 end)
nil
Link to this section Summary
Functions
Filters a value and maps it over a function
Maps an option over a function
Maps an option over a function or uses the provided default
Transforms an Option into a Result
Uses the default if nil
Link to this section Types
Option type.
Link to this section Functions
Filters a value and maps it over a function.
iex> import Lonely.Option
...> filter_map(1, fn x -> x > 0 end, fn x -> x + x end)
2
iex> import Lonely.Option
...> filter_map(-1, fn x -> x > 0 end, fn x -> x + x end)
-1
iex> import Lonely.Option
...> filter_map(nil, fn x -> x > 0 end, fn x -> x + x end)
nil
Maps an option over a function.
iex> import Lonely.Option
...> map(1, fn x -> x + x end)
2
iex> import Lonely.Option
...> map(nil, fn x -> x + x end)
nil
Maps an option over a function or uses the provided default.
iex> import Lonely.Option
...> map_or(1, fn x -> x + x end, 0)
2
iex> import Lonely.Option
...> map_or(nil, fn x -> x + x end, 0)
0
Transforms an Option into a Result.
iex> import Lonely.Option
...> to_result(1, :boom)
{:ok, 1}
iex> import Lonely.Option
...> to_result(nil, :boom)
{:error, :boom}
Uses the default if nil.
iex> import Lonely.Option
...> with_default(1, 0)
1
iex> import Lonely.Option
...> with_default(nil, 0)
0