只开三扇门:完整示例与补充知识
这里保留原课的完整资料,供你按需查阅;主看板只讲本课的核心问题。
设计小而稳的公开 API,把分词细节藏进私有函数。
实现 TrailStats.count/1,从行 list 得到固定统计 struct。
让公开入口只接收行
本项目约定空白分隔词,字符数不包含换行。
原课完整示例(按说明选择运行环境)
defmodule TrailStats.Stats do
@enforce_keys [:lines, :words, :chars]
defstruct [:lines, :words, :chars]
end
defmodule TrailStats do
alias TrailStats.Stats
# 对外只公开 count/1
def count(lines) do
%Stats{
lines: length(lines),
words: Enum.reduce(lines, 0, &(&2 + word_count(&1))),
chars: lines |> Enum.join() |> String.length()
}
end
defp word_count(line), do: line |> String.split() |> length()
endTrailStats.count(["长安 春风", "又一程"]) 返回行 2、词 3、字符 8 的 struct。
完整示例的执行步骤
- struct 固定三项输出,避免 map 键随手变化。
count/1只接内部数据,不关心路径。- 分词规则藏在
word_count/1,以后可单独替换。
原课补充说明
模块对外开的门越多,未来越难改。项目只公开调用者真正需要的函数。
统计模块接收已经清洗的行,不再读文件。字符、词、行的规则写在同一处。
内部 helper 使用 defp。调用者看见稳定结果,不需要知道中间 list 怎样生成。
符号与术语对照
def- 定义公开函数。
defp- 定义只供当前模块使用的私有函数。
%Stats{}- 返回固定字段的统计结果。
- 公开 API
- 模块外可以依赖的函数和数据形状。
- 实现细节
- 模块内部可修改而不影响调用者的步骤,通常放在私有函数。
原课完整练习
补全空输入测试。
练习起点
assert TrailStats.count([]) == %TrailStats.Stats{
lines: ____,
words: ____,
chars: ____
}三项都为 0。
查看提示
空输入没有行、词和字符。
查看原课答案
答案参考
# 空输入是公开 API 的重要边界
assert TrailStats.count([]) == %TrailStats.Stats{
lines: 0,
words: 0,
chars: 0
}为什么 word_count/1 使用 defp?
它只是 count/1 的实现细节,调用者不需要依赖它。
原课要点
- 公开 API 要小而明确。
- 模块之间传稳定数据,不传隐含状态。
- 实现细节用私有函数收好。