Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Erlang函数之外声明变量_Erlang - Fatal编程技术网

在Erlang函数之外声明变量

在Erlang函数之外声明变量,erlang,Erlang,我目前正在通读,并实现了以下示例: get_weather(City) -> Weather = [{toronto, rain}, {montreal, storms}, {london, fog}, {paris, sun}, {boston, fog}, {vancouver, snow}], [Locatio

我目前正在通读,并实现了以下示例:

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

有没有办法在函数作用域之外声明变量?我可以通过头文件执行此操作吗?

简短回答:否。变量只能在函数中定义

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

get_weather(toronto) -> rain;
get_weather(montreal) -> storms;
get_weather(london) -> fog;
get_weather(paris) -> sun;
get_weather(boston) -> fog;
get_weather(vancouver) -> snow.

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

简短回答:否。变量只能在函数中定义

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

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].

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

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

在头文件中,我们可以声明记录并导出它们,但不能导出列表等其他类型?@Suddi:记录不是值,甚至不是类型。它们是元组周围的语法糖。它更像是-define,而不是其他任何东西。在头文件中,我们可以声明记录并导出它们,但不能导出列表等其他类型?@Suddi:记录不是值,甚至不是类型。它们是元组周围的语法糖。它更像是定义,而不是其他任何东西。