Powered by AppSignal & Oban Pro

Keywords, functions, tuples

9_keyword.livemd

Keywords, functions, tuples

import IEx.Helpers

Keywords

list = [{"one", 1}, {"two", 2}]
[{"one", 1}, {"two", 2}]
list = [{:one, 1}, {:two, 2}]
[one: 1, two: 2]
# keyword data
# looks like a map
[one: 1, two: 2]
[one: 1, two: 2]

Tuple

{:arg1, :arg2, :options} |> Tuple.to_list() |> Enum.count()
3
# {:arg1, :arg2, [{:fast, true}, {:cheap, true}]}
# {:arg1, :arg2, [fast: true, cheap: true]}

# fast: true, cheap: true -> keyword
# we can omit the bracket if the last item is keyword

{:arg1, :arg2, fast: true, cheap: true}
{:arg1, :arg2, [fast: true, cheap: true]}
{:arg1, :arg2, fast: true, cheap: true} |> Tuple.to_list() |> Enum.count()
3

Functions

defmodule Args do
  def whats_going_on(first, options) do
    # inspected value is a keyword
    "first: #{first}, options: #{inspect(options)}"
  end
end
{:module, Args, <<70, 79, 82, 49, 0, 0, 7, ...>>, {:whats_going_on, 2}}
import Args
Args
whats_going_on(:one, :two)
"first: one, options: :two"
whats_going_on(:one, [{:one, 1}, {:two, 2}])
"first: one, options: [one: 1, two: 2]"
whats_going_on(:one, fast: true, cheap: true, reliable: true)
"first: one, options: [fast: true, cheap: true, reliable: true]"
exports(Args)
whats_going_on/2     
kw = [one: 1, two: 2]
# access behavior
kw[:one]
1