Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Giving access to Access

Giving access to Access

Take a quick glance at 5 cool ways to work with your data thanks to Elixir’s Access behaviour

Avatar for Natalie Perpepaj

Natalie Perpepaj

May 16, 2019
Tweet

Other Decks in Programming

Transcript

  1. Giving access to Access 5 cool ways to work with

    your data thanks to Elixir’s Access behaviour
  2. What is Access? • A behaviour that allows access to

    data structure keys • Supports keywords, maps, structs • Bracket Syntax ◦ Data[:key] ◦ Keywords and Maps ◦ Returns nil • Dot Syntax ◦ Data.key ◦ Maps and Structs ◦ Raises error
  3. Callbacks • fetch(data, key) ◦ Returns tuple {ok, value} or

    :error • get_and_update(data, key, function) ◦ Returns tuple with old value and new data • pop(data, key) ◦ Returns tuple with old value and new data or default
  4. 1. Access.get(container, key, default \\ nil) • Returns the value

    of given key • Is the reason we have bracket notation • Used in Kernel macros such as get_in • artists["beyonce knowles"] • Access.get(artists, "beyonce knowles") ◦ => %{ age: 37, songs: [ %{genre: "bounce", title: "formation"}, %{genre: "r&b", title: "beautiful liar"} ], stage_name: "beyonce” } • Artists[“the strokes”] ◦ => nil • Access.get(artists, "the strokes", %{stage_name: "the strokes"}) ◦ => %{stage_name: "the strokes"}
  5. Access.key(key, default \\ nil) • Returns a function • Purpose

    of the function is to access the value for the given key • put_in(artists, [Access.key("natalie", %{}), Access.key(:age)], 25) ◦ => %{ age: 37, songs: [ %{genre: "bounce", title: "formation"}, %{genre: "r&b", title: "beautiful liar"} ], stage_name: "beyonce” , "natalie" => %{age: 25} }
  6. Access.all( ) • Returns function that accesses all elements in

    a list • get_in(artists, ["beyonce knowles", :songs, Access.all, :genre]) ◦ => ["bounce", "r&b"]
  7. Access.filter(function) • Returns a function that can access elements matching

    given guard • get_in(artists, ["elvis aaron presley",:songs, Access.filter(&(&1.genre == "classic rock")), :title]) ◦ =>[“always on my mind”]
  8. Access.at(index) • Returns a function that access given list index

    • put_in(artists, ["elvis aaron presley", :songs, Access.at(1), :title], "brand new tunes") ◦ => %{beyone map…,%{ age: nil, songs: [ %{genre: "pop", title: "can't help falling in love"}, %{genre: "classic rock", title: "brand new tunes"}], stage_name: "elvis” }}
  9. Recap Access.get => returns value for provided key Access.key =>

    returns function to access provided key Access.all => returns function that accesses all elements in a list Access.filter => returns function that accesses specific elements in a list Access.at => returns function that accesses particular element in list