Elixir Todo List Exercise

From ElixirBlocks
Jump to: navigation, search
defmodule TodoList do
  defstruct todos: []

  def start do
    loop(%TodoList{})
  end

  def loop(state) do
    IO.puts("Todo List:")
    IO.inspect state.todos
    IO.inspect "add todo"
    todo = IO.gets("Enter Todo: ") |> String.trim()
    result = add_todo(state, todo)
    loop(result)

  end

  defp add_todo(state, todo) do
    %TodoList{state | todos: state.todos ++ [todo]}
  end

end

defmodule TodoList do
  defstruct todos: []

  def start do
    loop(%TodoList{})
  end

  def loop(state) do
    IO.puts("Todo List:")
    IO.inspect state.todos

    IO.puts("\nOptions:")
    IO.puts("1. Add Todo")
    IO.puts("2. Mark Todo as Done")
    IO.puts("3. Exit")

    case IO.gets("Select an option: ") |> String.trim() |> String.to_integer() do
      1 -> 
        todo = IO.gets("Enter Todo: ") |> String.trim()
        new_state = add_todo(state, todo)
        IO.inspect new_state
        loop(new_state)
      2 ->
        index = IO.gets("Enter index of Todo to mark as done: ") |> String.trim() |> String.to_integer()
        new_state = mark_todo_as_done(state, index)
        loop(new_state)
      3 -> 
        IO.puts("Goodbye!")
        :ok
      _ -> 
        IO.puts("Invalid option. Please try again.")
        loop(state)
    end
  end

  defp add_todo(state, todo) do
    %TodoList{state | todos: state.todos ++ [todo]}
  end

  defp mark_todo_as_done(state, index) do
    # fix
  end


end



defmodule TodoList do
  defstruct todos: []
  def start do
    loop(%TodoList{})
  end

  def loop(state) do
    IO.inspect state.todos
    todo = IO.gets("Enter Todo: ") |> String.trim()
    result = add_todo(state, todo)
    loop(result)
  end

  defp add_todo(state, todo) do
     result =  [todo | state.todos]
    %TodoList{todos: result}
  end
end