Created
February 12, 2016 05:59
-
-
Save jmsevold/012c148aa794af1fee34 to your computer and use it in GitHub Desktop.
Implementing a todo list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Todo do | |
use GenServer | |
# wrap calls to GenServer in public functions | |
def start(list) do | |
{:ok, todo_list} = GenServer.start(__MODULE__,list) | |
todo_list | |
end | |
def add_todo(todo_list,todo) do | |
GenServer.cast(todo_list, {:add_todo, todo}) | |
end | |
def remove_todo(todo_list,todo) do | |
GenServer.cast(todo_list, {:remove_todo, todo}) | |
end | |
def get_list(todo_list) do | |
GenServer.call(todo_list, :list) | |
end | |
### | |
# GenServer API | |
### | |
def handle_cast({:add_todo, todo}, todo_list) do | |
{:noreply, [todo | todo_list]} | |
end | |
def handle_cast({:remove_todo, todo}, todo_list) do | |
{:noreply, Enum.filter(todo_list, fn(item) -> item != todo end)} | |
end | |
def handle_call(:list, _from, list) do | |
{:reply, list, list} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment