Skip to content

Instantly share code, notes, and snippets.

@jbranchaud
Last active February 5, 2016 21:36
Show Gist options
  • Save jbranchaud/307a12a92e3c59e73877 to your computer and use it in GitHub Desktop.
Save jbranchaud/307a12a92e3c59e73877 to your computer and use it in GitHub Desktop.
playing with arrays in elixir
defmodule Listless do
def first([]), do: nil
def first([head|_]) do
head
end
def last([]), do: first []
def last([head|[]]), do: head
def last(list) do
[_|tail] = list
last tail
end
def get([], _), do: nil
def get(list, 0), do: first list
def get(list, index) do
[_|tail] = list
get tail, (index - 1)
end
end
Listless.first []
Listless.first [1,2,3]
Listless.last []
Listless.last [1,2,3]
Listless.get [], 1
Listless.get [1,2,3], 0
Listless.get [1,2,3,4], 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment