头部和尾部
- 用管道运算符来表示列表
[头部 | 尾部]
[1,2,3]
表示为[ 1 | [ 2 | [ 3 | [ ] ] ] ]
iex(4)> [ 1 | [ 2 | [ 3 | [ ] ] ] ]
[1, 2, 3]
iex(5)> [ head | tail ] = [ 1,2,3]
[1, 2, 3]
iex(6)> head
1
iex(7)> tail
[2, 3]
iex(8)>
头部和尾部来处理列表
- 计算列表的长度
1、空列表的长度为 0
2、列表长度等于列表尾部的长度加1
defmodule MyList do
def len([]), do: 0
def len([_head | tail]), do: 1 + len(tail)
end
_head
使用了特殊变量_
(下划线),因为在len函数内没有调用到
运行
iex(10)> c "mylist.exs"
warning: redefining module MyList (current version defined in memory)
mylist.exs:1
[MyList]
iex(11)> MyList.len([3,4,5,6])
4
iex(12)> MyList.len(["cat","dog","durk"])
3
使用头部和尾部来构造列表
- 定义一个函数,返回一个包含每个数字的平方的列表
defmodule MyList1 do
def square([]), do: []
def square([head | tail]), do: [head * head | square(tail)]
end
创建映身函数
- 定义一个
map函数
,接收一个列表和一个函数 ,返回一个新列表,其元素为原列表中的每个元素应用于传入的函数后的结果
defmodule MyList2 do
def map([], _func), do: []
def map([head | tail], func), do: [func.(head) | map(tail, func)]
end
运行
iex(14)> c "mylist2.exs"
warning: redefining module MyList2 (current version defined in memory)
mylist2.exs:1
[MyList2]
iex(15)> MyList2.map([1,2,3],fn (n) -> n*n end)
[1, 4, 9]
iex(16)> MyList2.map([1,2,3],fn (n) -> n+1 end)
[2, 3, 4]
iex(17)> MyList2.map([1,2,3],fn (n) -> n>1 end)
[false, true, true]
iex(18)> MyList2.map([1,2,3],&(&1 + 2))
[3, 4, 5]
在递归过程中跟踪值
- 实现列表中每个元素的总和
- 递归中的total(变量)可以通过传入函数的参数里
defmodule MyList do
def sum([], total), do: total
def sum([head | tail], total), do: sum(tail, head + total)
end
运行
iex(20)> MyList.sum([1,2,3],0)
6
调用
sum
函数需要转入初始值 0,可以通过私有函数来优化
defmodule MyList do
def sum(list), do: _sum(list, 0)
# 私有方法
defp _sum([], total), do: total
defp _sum([head | tail], total), do: _sum(tail, head + total)
end
运行
iex(22)> MyList.sum([3,4,5])
12
生成求和函数
defmodule Mylist do
def reduce([], value,_) do
value
end
def reduce([head | tail], value, func) do
reduce(tail, func.(head,value), func)
end
end
运行:
iex(1)> c "reduce.exs"
[Mylist]
iex(2)> Mylist.reduce([1,2,3,4,5],0,&(&1+&2))
15
iex(3)> Mylist.reduce([1,2,3,4,5],1,&(&1*&2))
120
更复杂的列表模式
|
连接运算符的左边允许有多个值
iex(4)> [1,2,3 | [4,5,6]]
[1, 2, 3, 4, 5, 6]
iex(5)>
- 调换字符的位置的函数实例
defmodule Swapper do
def swap([]), do: []
def swap([a,b | tail ]),do: [b ,a | swap(tail)]
def swap([_]),do: raise "单个元素无法匹配"
end
运行
iex(5)> c "swap.exs"
[Swapper]
iex(6)> Swapper.swap([1,2,3,4,5,6])
[2, 1, 4, 3, 6, 5]
iex(7)> Swapper.swap([1,2,3,4,5,6,7])
** (RuntimeError) 单个元素无法匹配
swap.exs:4: Swapper.swap/1
swap.exs:3: Swapper.swap/1
列表的列表
实例:读取特定区域的天气情况
- 数据源 weather.exs
def test_data do
[
[1366225622,26,15,0.125],
[1366225622,27,15,0.35],
[1366225622,28,15,0.45],
[1366225622,26,15,0.65],
[1366225622,27,15,0.25],
[1366225622,29,15,0.15]
]
end
[ 时间,地区id ,温度,湿度 ]
weather函数 weather1.exs
defmodule WeatherHistory do
def for_location([],target_loc), do: []
def for_location( [head = [ _, target_loc, _ , _] | tail ],target_loc) do
[head | for_location(tail,target_loc)]
end
def for_location([_| tail],target_loc), do: for_location(tail,target_loc)
end