Files
marqdo/doc/tutorial/06-函数.md
T
cflmyandCursor d7924ea8c7 Add Marqdo Chinese syntax tutorial under doc/tutorial/
13 chapters plus a README index covering syntax, variables, functions,
control flow, collections, objects/inheritance, modules and the CLI.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-24 14:45:26 +08:00

189 lines
2.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 第 6 章:函数
## 6.1 定义函数
在 Marqdo 中,函数用 `##`(及更深)标题定义:
```markdown
## 加一
+ `n`
**n + 1**
```
- `## 加一` —— 函数名
- `+ `n`` —— 参数
- `**n + 1**` —— 返回值(**粗体 = 返回**)
函数可以挂在 `# main` 之下作为嵌套函数,也可以作为顶层自由函数。
## 6.2 调用函数
使用 `>` 调用(具名参数或位置参数):
```markdown
# main
> greet who=World # 具名参数
> greet World # 位置参数
## greet
+ `who`
> print text=Hello, `who`!
---
```
### 具名 vs 位置
```markdown
> 问候 谁=Marqdo # 具名:名=值
> 问候 Marqdo # 位置:按形参顺序
```
二者可混用:位置实参按「尚未被具名绑定的形参」从左到右填充。
> 具名实参的值可以含空格,直到下一个 `名=` 边界;位置实参是单个词法单元(不含空格)。
## 6.3 参数与默认值
可选参数用 `=默认值`:
```markdown
## 问候
+ `谁`
+ `礼貌`=False
1. `礼貌`
> print text=您好,`谁`!
2. *
> print text=嗨,`谁`!
```
调用:
```markdown
> 问候 谁=小明
> 问候 谁=小明 礼貌=True
```
## 6.4 返回值:`**…**`
用 `**…**` 返回表达式结果:
```markdown
## 加一
+ `n`
**n + 1**
```
调用并绑定结果:
```markdown
# main
*b = > 加一 n=1*
> print text=`b` # 2
```
### 返回 None:`****`
`****`(或空粗体 `**` + 空白 + `**`)返回 `None` 并结束函数体:
```markdown
## 静默
+ `x`
****
```
### 字符串返回
```markdown
## 问候语
+ `谁`
**"你好," + 谁 + "!"**
```
## 6.5 结束函数体:`---` / `***`
对于**没有返回值、只有副作用**的函数,用单独一行 `---` 或 `***` 结束函数体,避免后续兄弟语句被吞掉:
```markdown
# main
> 问候 谁=World
## 问候
+ `谁`
> print text=Hello, `谁`!
---
## 下一个函数
...
```
> `---` 仅在**函数体顶层单独一行**时表示「结束本函数」;文件开头的成对 `---` 是 frontmatter,不会混淆。
## 6.6 完整示例
```markdown
# main
> 问候 谁=Alice 礼貌=True
## 问候
+ `谁`
+ `礼貌`=False
1. `礼貌`
> print text=您好,`谁`!
2. *
> print text=嗨,`谁`!
---
## 加一
+ `n`
**n + 1**
```
输出:
```text
您好,Alice!
```
## 6.7 函数嵌套(标题深度)
嵌套辅助函数用更深的标题:
```markdown
# main
> 处理 名字=小明
## 处理
+ `名字`
*上 = > 大写 文本=`名字`*
> print text=`上`
### 大写
+ `文本`
**> str `文本`**
```
> 深度约定:`##` 是 `#` 的子级,`###` 是 `##` 的子级……按标题深度嵌套。
## 6.8 下一步
你已经会封装函数了。接下来学习[第 7 章:条件分支](./07-条件分支.md)。