声明变量的函数二郎
问题描述:
我目前正在通过learn you some Erlang读书外,我已经实现了下面的例子:声明变量的函数二郎
get_weather(City) ->
Weather = [{toronto, rain},
{montreal, storms},
{london, fog},
{paris, sun},
{boston, fog},
{vancouver, snow}],
[LocationWeather || {Location, LocationWeather} <- Weather, Location =:= City].
这个例子能正常工作,但如果我要声明的变量Weather
之外的功能,我得到的错误:
solve.erl:5: syntax error before: Weather
solve.erl:2: function get_weather/1 undefined
有没有办法声明变量之外的函数范围?我可以通过头文件来做到这一点吗?
答
简答题:没有。变量只能在函数中定义。
来实现你的函数另一种方法是使用模式匹配函数头:
get_weather(toronto) -> rain;
get_weather(montreal) -> storms;
get_weather(london) -> fog;
get_weather(paris) -> sun;
get_weather(boston) -> fog;
get_weather(vancouver) -> snow.
通过这种方法,你就根本不需要变量。你也可以得到结果作为单个原子,我认为这是一个比在列表中返回单个原子更好的设计。
答
另一种方法是定义返回的数据列表的功能:
weather_data() -> [{toronto, rain},
{montreal, storms},
{london, fog},
{paris, sun},
{boston, fog},
{vancouver, snow}].
get_weather() ->
[LocationWeather || {Location, LocationWeather} <- weather_data(), Location =:= City].
怎么样的头文件中,我们可以声明'records'并将其出口,而不是其他类型,如'lists'? – Suddi
@Suddi:记录不是值或甚至类型。它们是元组周围的语法糖。它比其他任何东西更像'-define'。 –