Advertisement
PadmaJS

Untitled

Oct 12th, 2021
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. defmodule Calculator do
  2. use GenServer
  3.  
  4. def init(val) do
  5. {:ok, val}
  6. end
  7.  
  8. def handle_cast({:add, num}, state) do
  9. {:noreply, state + num}
  10. end
  11.  
  12. def handle_cast({:sub, num}, state) do
  13. {:noreply, state - num}
  14. end
  15.  
  16. def handle_cast({:mult, num}, state) do
  17. {:noreply, state * num}
  18. end
  19.  
  20. def handle_cast({:div, num}, state) do
  21. {:noreply, div(state, num)}
  22. end
  23.  
  24. def handle_call(:get_result, _ , state) do
  25. {:reply, state, state}
  26. end
  27.  
  28. def start(num \\ 0) do
  29. GenServer.start(Calculator, num)
  30. end
  31.  
  32. def add(pid, num) do
  33. GenServer.cast(pid, {:add, num})
  34. GenServer.call(pid, :get_result)
  35. end
  36.  
  37. def sub(pid, num) do
  38. GenServer.cast(pid, {:sub, num})
  39. GenServer.call(pid, :get_result)
  40. end
  41.  
  42. def mult(pid, num) do
  43. GenServer.cast(pid, {:mult, num})
  44. GenServer.call(pid, :get_result)
  45. end
  46.  
  47. def divi(pid, num) do
  48. GenServer.cast(pid, {:div, num})
  49. GenServer.call(pid, :get_result)
  50. end
  51. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement