七周七语言 Erlang第一天编程习题解答

来源:互联网 发布:长春盘古网络咋样 编辑:程序博客网 时间:2024/06/11 01:45

1. 写一个函数, 用递归返回字符串中的单词数。


-module(word).-export([word_count/1]).word_count([]) -> 1;word_count([32 | Rest]) -> 1 + word_count(Rest);word_count([First | Rest]) -> 0 + word_count(Rest).

这个题主要是erlang中字符串就是一个ascii码的数组, 计单词数就是看多少个空格,空格值为32, 还有一个就是erlang的模式匹配和递归。


2.写一个递归计数到10的函数。


-module(count).-export([count10/1]).count10(10) -> io:format("Count:~w~n", [10]);count10(N) -> io:format("Count:~w~n",[N]), count10(N+1).

这个io:format第一天内容没有讲,可以理解成类似 printf 之类的, 就是一个标准输出的格式化,主要是模式匹配和递归。



原创粉丝点击