Advertisement
Guest User

Untitled

a guest
Jul 19th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. list = TodoList.new
  2. |> TodoList.add_entry(%{date: {2019, 08, 08}, title: 'Dentist'})
  3. |> TodoList.add_entry(%{date: {2019, 08, 08}, title: 'Doctor'})
  4.  
  5. todo_list =
  6. %TodoList{
  7. auto_id: 3,
  8. entries: %{
  9. 1 => %{date: {2019, 8, 8}, id: 1, title: 'Dentist'},
  10. 2 => %{date: {2019, 8, 8}, id: 2, title: 'Doctor'}
  11. }
  12. }
  13.  
  14. # create a references for entries
  15. entries = todo_list.entries
  16.  
  17. # To update a value in the entry
  18. {:ok , entry} = Map.fetch(todo_list.entries, 1)
  19. entry = %{date: {2019, 8, 8}, id: 1, title: 'Dentist'}
  20.  
  21. # Update the found entry
  22. new_entry = Map.put(entry, :title, 'Doctor')
  23.  
  24. # Construct new copy of entries, with the update new_entry
  25. new_entries = Map.put(entries, new_entry.id, new_entry)
  26.  
  27. # Return a new TodoList, this is how it works in functional programming.
  28. %TodoList{ todo_list | entries: new_entries }
  29.  
  30.  
  31. entry = %{date: {2019, 8, 8}, id: 1, title: 'Dentist'}
  32. update_func = &Map.put(&1, :title, 'Doctor')
  33. update_func = &Map.put(%1, :date, {2019, 8, 8})
  34.  
  35. # To make the function more composable, allow it to accept function as a lambda,
  36. # Now the function is flexible enough to keys based on the function passed in
  37. def update_entry(todo_list, id, updater_func) do
  38. case Map.fetch(todo_list.entries, entry_id) do
  39. :error ->
  40. todo_list
  41. {:ok ,old_entry} ->
  42. new_entry = updater_func.(old_entry)
  43. new_entries = Map.put(todo_list.entries, new_entry.id, new_entry)
  44. %TodoList{ todo_list | entris: new_entries }
  45. end
  46. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement