Skip to content

Commit 3129013

Browse files
benluojulienrf
authored andcommitted
add code tab in _zh-cn/overviews/scala3-book/fp-pure-functions.md
1 parent c3fd0a3 commit 3129013

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

_zh-cn/overviews/scala3-book/fp-pure-functions.md

+18-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ Scala 提供的另一个帮助您编写函数式代码的特性是编写纯函
3939

4040
这些 `String` 方法也是纯函数:
4141

42-
-`isEmpty`
42+
- `isEmpty`
4343
- `length`
4444
- `substring`
4545

@@ -85,17 +85,34 @@ Scala 集合类上的大多数方法也可以作为纯函数工作,包括 `dro
8585
要在 Scala 中编写纯函数,只需使用 Scala 的方法语法编写它们(尽管您也可以使用 Scala 的函数语法)。
8686
例如,这是一个将给定输入值加倍的纯函数:
8787

88+
{% tabs fp-pure-function %}
89+
{% tab 'Scala 2 and 3' %}
8890
```scala
8991
def double(i: Int): Int = i * 2
9092
```
93+
{% endtab %}
94+
{% endtabs %}
9195

9296
如果您对递归感到满意,这是一个计算整数列表之和的纯函数:
9397

98+
{% tabs fp-pure-recursive-function class=tabs-scala-version %}
99+
{% tab 'Scala 2' %}
100+
```scala
101+
def sum(xs: List[Int]): Int = xs match {
102+
case Nil => 0
103+
case head :: tail => head + sum(tail)
104+
}
105+
```
106+
{% endtab %}
107+
108+
{% tab 'Scala 3' %}
94109
```scala
95110
def sum(xs: List[Int]): Int = xs match
96111
case Nil => 0
97112
case head :: tail => head + sum(tail)
98113
```
114+
{% endtab %}
115+
{% endtabs %}
99116

100117
如果您理解该代码,您会发现它符合纯函数定义。
101118

0 commit comments

Comments
 (0)