Pearls Flashcards
IEX Break Trigger
iex:break
How do you “peek” at data in the middle of a pipeline?
|> IO.inspect(label: “description”)
Whereas Map.put/3 allows you to edit a single value in a map, what syntax can you use to edit multiple values in one call?
Use the | syntax
%{data | name: “Thor”, age: 61, updated_at: DateTime.utc_now()}
How do you update deeply nested data in a map?
The update_in/3 standard library function takes a map (or another data type that implements the Access protocol), a list of keys, and a function that provides the updated value.
iex> %{“john” => %{age: 27}, “meg” => %{age: 23}}
iex> |> update_in([“john”, :age], &(&1 + 1))
%{“john” => %{age: 28}, “meg” => %{age: 23}}
Note: update_in is in the standard library, not via Map.update_in
What are the standard library functions and macros that deal with nested data?
Kernel.get_in/2 function Kernel.update_in/3 function Kernel.update_in/2 macro Kernel.get_and_update_in/3 function Kernel.get_and_update_in/2 macro Kernel.put_in/3 function Kernel.put_in/2 macro Kernel.pop_in/2 function Kernel.pop_in/1 macro
What does the destructure function do for a pair of lists?
It uses pattern matching to fill variables in the first list with values in the second list, not requiring list sizes to be the same. If the second list is longer, it’s submission to the first list is simply truncated. If the second list is shorter, the remaining values on the first list become nil.
destructure([a,b,c], [1,2,3,4]) gives [1,2,3] and a==1, b==2, c==3.
destructure([a,b,c,d], [1,2,3]) gives [1,2,3,nil]
So the first list is changed as a side effect to the function