列表与递归

头部和尾部

[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" })

posted @ 2019-09-10 13:42  GodL  阅读(390)  评论(0编辑  收藏  举报