2016-08-21 68 views
2

我目前正在通過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 

有沒有辦法聲明變量之外的函數範圍?我可以通過頭文件來做到這一點嗎?

回答

5

簡答題:沒有。變量只能在函數中定義。

來實現你的函數另一種方法是使用模式匹配函數頭:

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

通過這種方法,你就根本不需要變量。你也可以得到結果作爲單個原子,我認爲這是一個比在列表中返回單個原子更好的設計。

+0

怎麼樣的頭文件中,我們可以聲明'records'並將其出口,而不是其他類型,如'lists'? – Suddi

+2

@Suddi:記錄不是值或甚至類型。它們是元組周圍的語法糖。它比其他任何東西更像'-define'。 –

2

另一種方法是定義返回的數據列表的功能:

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