关键字列表是一种键值对数据结构。
[month: "April", year: 2018]
关键字列表是由{key, value}元组组成的列表,也可以写成这种形式,但更短的语法使用得更广泛。
[month: "April"] == [{:month, "April"}]
# => true
关键字列表中的键必须是原子,但值可以是任何东西。每个键可以使用多次。关键字列表中的键值对是有序的。
你可以用处理列表的相同方法来处理关键字列表,也可以使用Keyword模块。
你是一家高档餐厅的经理,餐厅有一个颇具规模的酒窖。你的许多顾客都是要求很高的葡萄酒爱好者。要为某位特定的顾客挑到合适的那瓶葡萄酒,并非易事。
作为一名精通技术的餐厅老板,你决定写一个应用,让客人能按自己的偏好筛选你收藏的葡萄酒,从而加快选酒的过程。
在应用的欢迎界面上,你想为每种葡萄酒颜色显示一段简短的说明。
实现 WineCellar.explain_colors/0 函数。它不接受任何参数,返回一个关键字列表,以葡萄酒颜色为键,以说明为值。
| 颜色 | 说明 |
|---|---|
:white |
Fermented without skin contact. |
:red |
Fermented with skin contact using dark-colored grapes. |
:rose |
Fermented with some skin contact, but not enough to qualify as a red wine. |
一瓶葡萄酒用一个由葡萄品种、年份和原产国组成的三元组表示。葡萄酒按颜色存储在关键字列表中。
[
white: {"Chardonnay", 2015, "Italy"},
white: {"Pinot grigio", 2017, "Germany"},
red: {"Pinot noir", 2016, "France"},
rose: {"Dornfelder", 2018, "Germany"}
]
实现 WineCellar.filter/3 函数。它应接受一个葡萄酒的关键字列表、一个颜色原子和一个选项的关键字列表,选项的默认值为 []。函数应返回指定颜色的葡萄酒列表。
WineCellar.filter(
[
white: {"Chardonnay", 2015, "Italy"},
white: {"Pinot grigio", 2017, "Germany"},
red: {"Pinot noir", 2016, "France"},
rose: {"Dornfelder", 2018, "Germany"}
],
:white
)
# => [
# {"Chardonnay", 2015, "Italy"},
# {"Pinot grigio", 2017, "Germany"}
# ]
扩展 WineCellar.filter/3 函数。当传入 :year 选项时,函数应返回指定颜色中来自指定年份的葡萄酒列表。
使用已经实现好的 WineCellar.filter_by_year/2 函数。它接受一个葡萄酒列表和一个年份作为参数,返回来自指定年份的葡萄酒列表。
WineCellar.filter(
[
white: {"Chardonnay", 2015, "Italy"},
white: {"Pinot grigio", 2017, "Germany"},
red: {"Pinot noir", 2016, "France"},
rose: {"Dornfelder", 2018, "Germany"}
],
:white,
year: 2015
)
# => [
# {"Chardonnay", 2015, "Italy"}
# ]
扩展 WineCellar.filter/3 函数。当传入 :country 选项时,函数应返回指定颜色中来自指定国家的葡萄酒列表。
使用已经实现好的 WineCellar.filter_by_country/2 函数。它接受一个葡萄酒列表和一个国家作为参数,返回来自指定国家的葡萄酒列表。
确保当同时传入 :year 和 :country 选项时,无论顺序如何,函数都能正常工作。
WineCellar.filter(
[
white: {"Chardonnay", 2015, "Italy"},
white: {"Pinot grigio", 2017, "Germany"},
red: {"Pinot noir", 2016, "France"},
rose: {"Dornfelder", 2018, "Germany"}
],
:white,
year: 2015,
country: "Germany"
)
# => []