Skip to content

Instantly share code, notes, and snippets.

@samnang
Last active February 17, 2017 21:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samnang/394d9dbec5fceddb029f5f08d89b1a42 to your computer and use it in GitHub Desktop.
Save samnang/394d9dbec5fceddb029f5f08d89b1a42 to your computer and use it in GitHub Desktop.
Guard clause vs Control Structures in #Elixir?

1. Using guard

defmodule MyList do
  def max(list), do: _max(list, nil)

  defp _max([], max_value), do: max_value
  defp _max([head | tail], nil), do: _max(tail, head)

  # using guard
  defp _max([head | tail], max_value) when max_value < head, do: _max(tail, head)
  defp _max([head | tail], max_value), do: _max(tail, max_value)
end

2. Using cond control structures

defmodule MyList do
  def max(list), do: _max(list, nil)

  defp _max([], max_value), do: max_value
  defp _max([head | tail], nil), do: _max(tail, head)

  # using cond
  defp _max([head | tail], max_value) do
    cond do
      max_value < head -> _max(tail, head)
      true -> _max(tail, max_value)
    end
  end
end
@bcardarella
Copy link

bcardarella commented Feb 12, 2017

Guard clauses happen at compile-time and can yield an optimization that cond cannot. However, guards are limited in what they can do and access, being compile-time. So cond has more flexibility.

@samnang
Copy link
Author

samnang commented Feb 17, 2017

@bcardarella Guard clauses provide performance vs cond provides flexibility, sound like go with guard clauses first unless it doesn't provide flexibility in the scenarios that are trying to solve.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment