/

声明函数

你可以使用 .function 文档 ↗ 函数来声明函数(在 Quarkdown 中,一切皆函数!)。

它接受两个参数:函数名与其主体。随后该函数就可以像普通函数调用一样被调用 —— 请参阅函数调用语法

示例 1

.function {helloworld}
    Hello, world!

.helloworld

Hello, world!

参数

主体参数是一个 lambda ,函数的每个参数都是该 lambda 块的一个参数。你可以在函数主体中将每个参数作为变量 来访问,在 Quarkdown 中,变量本质上就是一个无参数的函数。

示例 2

.function {greet}
    to from:
    Hello, .to from .from!

.greet {world} {John}

Hello, world from John!

提示:你可以为参数命名以提高可读性:

.greet {world} from:{John}

可选参数

如果函数参数以问号 ? 结尾,它就变为可选参数。当你未提供相应参数时,它会收到 None 值。

示例 3

.function {greet}
    to from?:
    Hello, .to from .from!

.greet {world}

.greet {world} {John}

Hello, world from None!

Hello, world from John!

None 提供了一些有用的操作,例如用于模拟默认参数值的占位符 .otherwise

示例 4

.function {greet}
    to from?:
    Hello, .to from .from::otherwise {unnamed}!

.greet {world}

.greet {world} {John}

Hello, world from unnamed!

Hello, world from John!

块级参数

块级参数始终对应于函数的最后一个参数。声明它们没有特殊语法;只需照常定义函数即可。

示例 5

.function {myexample}
    title content:
    .box {.title}
        .content

.myexample {Example title}
    This is the content of the example.

Example title

This is the content of the example.

返回值

在 Quarkdown 中,没有 return 语句。每一条被执行的指令都会成为输出的一部分 —— 请参阅条件语句

示例 6

.function {myfunction}
    .if {.iseven {3}}
        A
    B

.myfunction

B

函数可以返回任意 Markdown 内容。

示例 7

.function {greet}
    to from:
    **Hello, .to** from .from!

.greet {world} from:{John}

Hello, world from John!

Quarkdown 是弱类型 的,因此函数可以返回任意类型的值。

示例 8

.function {area}
    width height:
    .multiply {.width} by:{.height}

The area of the rectangle is **.area {4} {2}**.

The area of the rectangle is 8.

示例 9

.function {isadult}
    age:
    .age::isgreater than:{18}

.if {.isadult age:{20}}
    You're an adult!

You’re an adult!

覆盖函数

函数可以在任何位置被重新声明,从该点起,在当前作用域内新定义会优先于先前的旧定义。

示例 10

.uppercase {Quarkdown}

.function {uppercase}
    text:
    .text::lowercase

.uppercase {Quarkdown}

QUARKDOWN

quarkdown

这种行为可以在命令行级别通过 --forbid-function-overwriting 选项禁用,当声明一个已被占用的函数名时会引发编译错误。