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

Types

t()

Option type

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

Link to this function filter_map(a, f, g) View Source
filter_map(t, (any -> boolean), (any -> t)) :: t

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
Link to this function map(a, f) View Source
map(t, (any -> t)) :: t

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
Link to this function map_or(a, f, default) View Source
map_or(t, (any -> t), any) :: t

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
Link to this function to_result(a, reason) View Source
to_result(t, any) :: Lonely.Result.t

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}
Link to this function with_default(a, default) View Source
with_default(t, any) :: any

Uses the default if nil.

iex> import Lonely.Option
...> with_default(1, 0)
1

iex> import Lonely.Option
...> with_default(nil, 0)
0