Today I Learned

hashrocket A Hashrocket project

`hd` in Guard Tests

The hd method in Elixir returns the head of a list. It's kind of like List.first, but raises an error on an empty list.

iex(0)> hd [1,2,3]
1
iex(1)> hd []
** (ArgumentError) argument error
    :erlang.hd([])

Browsing the docs, I learned something interesting: hd is allowed in guard tests.

Here's a contrived implementation of this behavior:

# example.ex
defmodule TestModule do
  def header(list) when hd(list) == 1, do: IO.puts "We did it"
end
iex(0)> TestModule.header([1,2,3])
We did it
:ok

When the guard's conditions aren't met, an error is raised:

iex(1)> TestModule.header([2,3,4])
** (FunctionClauseError) no function clause matching in TestModule.header/1
    iex:13: TestModule.header([2, 3, 4])

h/t Chris Erin & Micah Cooper

See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.