接下來(lái),我們會(huì)用一個(gè)更加完整的例子來(lái)鞏固前面學(xué)到的內(nèi)容。假設(shè)你有一個(gè)世界上各個(gè)城市的溫度值的列表。其中,一部分是以攝氏度表示,另一部分是華氏溫度表示的。首先,我們將所有的溫度都轉(zhuǎn)換為用攝氏度表示,再將溫度數(shù)據(jù)輸出。
%% This module is in file tut5.erl
-module(tut5).
-export([format_temps/1]).
%% Only this function is exported
format_temps([])-> % No output for an empty list
ok;
format_temps([City | Rest]) ->
print_temp(convert_to_celsius(City)),
format_temps(Rest).
convert_to_celsius({Name, {c, Temp}}) -> % No conversion needed
{Name, {c, Temp}};
convert_to_celsius({Name, {f, Temp}}) -> % Do the conversion
{Name, {c, (Temp - 32) * 5 / 9}}.
print_temp({Name, {c, Temp}}) ->
io:format("~-15w ~w c~n", [Name, Temp]).
35> c(tut5).
{ok,tut5}
36> tut5:format_temps([{moscow, {c, -10}}, {cape_town, {f, 70}},
{stockholm, {c, -4}}, {paris, {f, 28}}, {london, {f, 36}}]).
moscow -10 c
cape_town 21.11111111111111 c
stockholm -4 c
paris -2.2222222222222223 c
london 2.2222222222222223 c
ok
在分析這段程序前,請(qǐng)先注意我們?cè)诖a中加入了一部分的注釋。從 % 開(kāi)始,一直到一行的結(jié)束都是注釋的內(nèi)容。另外,-export([format_temps/1])
只導(dǎo)出了函數(shù) format_temp/1
,其它函數(shù)都是局部函數(shù),或者稱(chēng)之為本地函數(shù)。也就是說(shuō),這些函數(shù)在 tut5 外部是不見(jiàn)的,自然不能被其它模塊所調(diào)用。
在 shell 測(cè)試程序時(shí),輸出被分割到了兩行中,這是因?yàn)檩斎胩L(zhǎng),在一行中不能被全部顯示。
第一次調(diào)用 format_temps
函數(shù)時(shí),City 被賦予值 {moscow,{c,-10}}, Rest 表示剩余的列表。所以調(diào)用函數(shù) print_temp(convert_to_celsius({moscow,{c,-10}}))
。
這里,convert_to_celsius({moscow,{c,-10}})
調(diào)用的結(jié)果作為另一個(gè)函數(shù) print_temp
的參數(shù)。當(dāng)以這樣嵌套的方式調(diào)用函數(shù)時(shí),它們會(huì)從內(nèi)到外計(jì)算。也就是說(shuō),先計(jì)算 convert_to_celsius({moscow,{c,-10}})
得到以攝氏度表示的值 {moscow,{c,-10}}。接下來(lái),執(zhí)行函數(shù) convert_to_celsius
與前面例子中的 convert_length
函數(shù)類(lèi)似。
print_temp
函數(shù)調(diào)用 io:format 函數(shù),~-15w 表示以寬度值 15 輸出后面的項(xiàng) (參見(jiàn)STDLIB 的 IO 手冊(cè)。)
接下來(lái),用列表剩余的元素作參數(shù)調(diào)用 format_temps(Rest)
。這與其它語(yǔ)言中循環(huán)構(gòu)造很類(lèi)似 (是的,雖然這是規(guī)遞的形式,但是我們并不需要擔(dān)心)。再調(diào)用 format_temps
函數(shù)時(shí),City 的值為 {cape_town,{f,70}}
,然后同樣的處理過(guò)程再重復(fù)一次。上面的過(guò)程一直重復(fù)到列表為空為止。因?yàn)楫?dāng)列表為空時(shí),會(huì)匹配 format_temps([])
語(yǔ)句。此語(yǔ)句會(huì)簡(jiǎn)單的返回原子值 ok,最后程序結(jié)束。
更多建議: