頭部和尾部
[head | tail ] = [1] #head 1 tail [] [head | tail ] = [1, 2, 3] #head 1 tail [2, 3] [head | tail ] = [] #報錯
?
創建映射函數
我們可以使用一個函數來處理列表中的各個元素,如此可以接受更加復雜的處理,也可以根據傳入函數的功能做不同的處理。
def map([], _func), do: [] def map([ head | tail ], func), do: [func.(head) | map(tail, func)]Example.map [1,2,3,4], fn n -> n * n end #[1, 4, 9, 16]
?
在遞歸過程中跟蹤值
我們的目標是使用不可變狀態,所以不能再一個全局變量或者模塊級變量例存儲值。所以,我們以函數參數傳入
def sum([], total), do: total def sum([head | tail], total), do sum(tail, total + head)Example.sum([1,2,3,4], 0) #10#我們總要傳入一個初始值,可以如下改進 def sum(list), do: sum(list, 0)defp _sum([], total), do: total defp _sum([head | tail], total), do: sum(tail, total + head)
使用函數解決問題
def reduce([], value, _), do: value def reduce([head | tail], value, func), do: reduce(tail, func.(head, value), func) #使用匿名函數時在參數列表前加一個點(.)
Example.reduce
?
更復雜的列表
#交換相近的兩個數據,若是單數個數據就報錯 def swap([]), do: [] def swap([a, b | tail]), do: [b, a | swap(tail)] def swap([_]), do: raise "Can`t swap a list with an odd number of elements"
可以使用[a, ..., x | tail]匹配一組數據
# [ timestamp, location_id, temperature, rainfall ] 這組數據表示天氣 # 版本一 def for_location_27([]), do: [] def for_location_27([ [ time, 27, temp, rain ] | tail ]) do
[ [ time, 27, temp, rain ] | for_location_27(tail) ] #篩選出location_id為27的一組數據
end def for_location_27([ _ | tail ]), do: for_location_27(tail) #跳過格式不匹配的一組數據中的一個
#版本二
#更具傳入數據進行篩選
def for_location([], _target_loc), do: []
def for_location([ [ time, target_loc, temp, rain ] | tail ], target_loc) do
[ [ time, target_loc, temp, rain ] | for_location(tail, target_loc) ]
end
def for_location([ _ | tail ], target_loc), do: for_location(tail, target_loc)
#版本三
#將匹配函數簡化為:
def for_location( head = [ _, target_loc, _, _ ] | tail ], target_loc ), do: [ head | for_location(tail, target_loc) ]
?
List模塊提供的函數
連接。[1, 2, 3] ++ [4, 5, 6]
一維化。List.flatten([[[1], 2], [[[3]]]]) => [1, 2, 3]
折疊。List.foldl([1, 2, 3], "", fn value, acc -> "#{value}(#{acc})" end ) =>3(2(1()))
List.foldr([1, 2, 3], "", fn value, acc -> "#{value}(#{acc})" end ) ? =>1(2(3()))
合并、拆分。l = List.zip([ [1, 2, 3], [:a, :b, :c], ["cat", "dog"] ] ) =>[ {1, :a, "cat"}, {2, :b, "dog"}]
List.unzip( l ) => [ [ 1, 2 ], [ :a, :b ], [ "cat", "dog" ]
在列表里訪問元組。kw = [ {:name, "Dave"}, {:likes, "Programmin"}, {:where, "Dallas", "TX"} ]
List.keyfind(kw, :name, 0) {:name, "Dave"} 參數:列表,元組中數據值,數字在元組中的下標
List.keyfind(kw, "TX", 2) {:where, "Dallas", "TX"}
List.keyfind(kw, "TX", 1) nil
刪除元組。List.keydelete(kw, "TX", 2)
替換元組。List.keyreplace(kw, :name, 0, { :first_name, "Dave" })