声明Erlang函数之外的变量

时间:2016-08-21 02:09:05

标签: erlang

我目前正在阅读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

有没有办法在函数范围之外声明变量?我可以通过头文件来完成吗?

2 个答案:

答案 0 :(得分:4)

简答:不。变量只能在函数中定义。

实现函数的另一种方法是在函数头中使用模式匹配:

array ( '00' => 'x', 11 => 'y',)

通过这种方法,您根本不需要变量。您还可以将结果作为单个原子获得,我认为这比在列表中返回单个原子更好。

答案 1 :(得分:2)

另一种方法是定义一个返回数据列表的函数:

weather_data() -> [{toronto, rain}, 
                   {montreal, storms}, 
                   {london, fog}, 
                   {paris, sun}, 
                   {boston, fog},
                   {vancouver, snow}].
get_weather() ->
    [LocationWeather || {Location, LocationWeather} <- weather_data(), Location =:= City].
相关问题