The List Module in Action

The List module provides a set of functions that operate on lists.

 #
 # Concatenate lists
 #
 iex>​ [1,2,3] ++ [4,5,6]
 [1, 2, 3, 4, 5, 6]
 #
 # Flatten
 #
 iex>​ List.flatten([[[1], 2], [[[3]]]])
 [1, 2, 3]
 #
 # Folding (like reduce, but can choose direction)
 #
 iex>​ List.foldl([1,2,3], ​"​​"​, ​fn​ value, acc -> ​"​​#{​value​}​​(​​#{​acc​}​​)"​ ​end​)
 "3(2(1()))"
 iex>​ List.foldr([1,2,3], ​"​​"​, ​fn​ value, acc -> ​"​​#{​value​}​​(​​#{​acc​}​​)"​ ​end​)
 "1(2(3()))"
 #
 # Updating in the middle (not a cheap operation)
 #
 iex>​ list = [ 1, 2, 3 ]
 [ 1, 2, 3 ]
 iex>​ List.replace_at(list, 2, ​"​​buckle my shoe"​)
 [1, 2, "buckle my shoe"]
 #
 # Accessing tuples within lists
 #
 iex>​ kw = [{​:name​, ​"​​Dave"​}, {​:likes​, ​"​​Programming"​}, {​:where​, ​"​​Dallas"​, ​"​​TX"​}]
 [{:name, "Dave"}, {:likes, "Programming"}, {:where, "Dallas", "TX"}]
 iex>​ List.keyfind(kw, ​"​​Dallas"​, 1)
 {:where, "Dallas", "TX"}
 iex>​ List.keyfind(kw, ​"​​TX"​, 2)
 {:where, "Dallas", "TX"}
 iex>​ List.keyfind(kw, ​"​​TX"​, 1)
 nil
 iex>​ List.keyfind(kw, ​"​​TX"​, 1, ​"​​No city called TX"​)
 "No city called TX"
 iex>​ kw = List.keydelete(kw, ​"​​TX"​, 2)
 [name: "Dave", likes: "Programming"]
 iex>​ kw = List.keyreplace(kw, ​:name​, 0, {​:first_name​, ​"​​Dave"​})
 [first_name: "Dave", likes: "Programming"]