Member-only story

Elixir — Differences between hd and List.first

Malreddy Ankanna
2 min readOct 13, 2017

A tip to BOOST your elixir coding…

image credits: canva.com

To boost up your Elixir coding, you need to understand a few differences between these two even though they are used for the same purpose.

hd ( vs ) List.first [ diff…]

We all knew that hd & List.first are used to pick out the first element in a list . But, why two functions for the same purpose?
However, they differ slightly in dealing with the empty list [] and in guard tests.

Differences

  1. on Empty lists
    The function hd on empty list [] results in Argument Error
    The function List.first on empty list [] results in nil
  2. on guard tests
    The function hd is allowed in guard tests. In lined by the compiler.
    The function List.firstis not allowed in guard tests.

Lets check this in live…

Hope now you got some idea and understood where and when to use them.

--

--

Malreddy Ankanna
Malreddy Ankanna

Written by Malreddy Ankanna

Programmer & Writer, I write about coding, thoughts, ideas, personal musings, technical articles, and tutorials.https://bio.link/blackode

No responses yet