Erlang惯用编程:模式匹配与case语句孰优?代码对比解析
Great question—let’s break this down in the context of Erlang’s idiomatic style, since this is a common pitfall for folks new to the language!
1. 模式匹配 vs Case语句:Erlang的核心偏好
In Erlang, 模式匹配 is hands-down the preferred approach whenever possible. The language was built from the ground up to leverage pattern matching as a core tool for expressing logic cleanly.
Instead of cramming conditional branches into a single function with case, splitting logic into separate function clauses via pattern matching makes code more readable, modular, and aligned with how Erlang developers naturally think about problem-solving. case statements still have their place—like when you need to match against a value generated inside a function, rather than something that can be captured in the function header—but pattern matching is always the first choice for idiomatic Erlang.
2. sumOfMultiples实现:首选代码段一
Without a doubt, 代码段一是 the idiomatic Erlang implementation here. Let’s first look at both snippets clearly:
代码段一(模式匹配实现)
sumOfMultiples(Multiples, 1) -> 0; sumOfMultiples(Multiples, N) -> cal_multiples(Multiples, lists:seq(1, N-1), 0).
代码段二(Case语句实现)
sumOfMultiples(Multiples, N) -> case N of 1 -> 0; _ -> cal_multiples(Multiples, lists:seq(1, N-1), 0) end.
为什么代码段一更优?
- Follows Erlang’s core idioms: Splitting the function into two clauses based on the value of
Nis exactly how Erlang is meant to be written. Any experienced Erlang developer can immediately see what happens whenN=1versus any other value—no need to scan through a nestedcaseblock to parse logic. - Better readability: The pattern matching approach flattens the logic, avoiding the extra indentation and boilerplate of
case/end. It’s more concise and easier to scan at a glance. - Scalability: If you ever need to add more edge cases (like handling
N=0), you just add another function clause instead of expanding thecaseblock—this keeps the code clean as it grows.
内容的提问来源于stack exchange,提问作者Muhammad Lukman Low

