开始学习《七周七语言——理解多种编程范型》 下面是Erlang第一天的三道练习题
写一个函数,用递归返回字符串的单词数
%% 递归统计单词数
number_of_word(Text)->length(recur_count_word(Text,[],[])).
%% 递归统计单词
append_new_word(Words, Word)->(lists:append(Words, [Word]));
append_new_word(Words, [])->Words.
recur_count_word([], Word, Words)->append_new_word(Words, [Word]);
recur_count_word([First|Text] , Word, Words)->
if
(hd("a") =< First) and (First =< hd("z")) or (hd("A") =< First) and (First =< hd("Z"))
-> recur_count_word(Text, lists:append(Word, [First]), Words);
true
-> recur_count_word(Text, [], append_new_word(Words, [Word]))
end.
Erlang没有传统的赋值语句,只有模式匹配,利用模式匹配能更抽象的操作列表,而字符串本身也是个列表,自然也能利用模式匹配更好的解析它,配合递归,几乎没有判断语句。唯一要判断的地方就是字母的判断,这个我想可以通过正则来做,会更好一点,不过现在并不知道如何在Erlang中如何使用正则。
写一个递归统计到10的函数
count(0)->ok;
count(N)->count(N - 1), io:format("~p ", [N]).
count10()->count(10), io:format("~n").
简单递归,模式匹配的特性让递归出口分离表达。还有一点值得注意的是对于尾递归,Erlang会有优化,性能不比循环差。
写一个函数,在给定输入位{error, Message}或success的条件下,利用匹配相应地打出"success"或"error: message"
handler(success)->io:format("~p~n", [success]);
handler({error, Message})->io:format("error:~p~n", [Message]).
元组匹配。io:format第二个参数是输出列表,必须是列表。