File tree 1 file changed +18
-1
lines changed
_zh-cn/overviews/scala3-book
1 file changed +18
-1
lines changed Original file line number Diff line number Diff line change @@ -39,7 +39,7 @@ Scala 提供的另一个帮助您编写函数式代码的特性是编写纯函
39
39
40
40
这些 ` String ` 方法也是纯函数:
41
41
42
- -` isEmpty `
42
+ - ` isEmpty `
43
43
- ` length `
44
44
- ` substring `
45
45
@@ -85,17 +85,34 @@ Scala 集合类上的大多数方法也可以作为纯函数工作,包括 `dro
85
85
要在 Scala 中编写纯函数,只需使用 Scala 的方法语法编写它们(尽管您也可以使用 Scala 的函数语法)。
86
86
例如,这是一个将给定输入值加倍的纯函数:
87
87
88
+ {% tabs fp-pure-function %}
89
+ {% tab 'Scala 2 and 3' %}
88
90
``` scala
89
91
def double (i : Int ): Int = i * 2
90
92
```
93
+ {% endtab %}
94
+ {% endtabs %}
91
95
92
96
如果您对递归感到满意,这是一个计算整数列表之和的纯函数:
93
97
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' %}
94
109
``` scala
95
110
def sum (xs : List [Int ]): Int = xs match
96
111
case Nil => 0
97
112
case head :: tail => head + sum(tail)
98
113
```
114
+ {% endtab %}
115
+ {% endtabs %}
99
116
100
117
如果您理解该代码,您会发现它符合纯函数定义。
101
118
You can’t perform that action at this time.
0 commit comments