SML编程:从基础声明到高阶函数
立即解锁
发布时间: 2025-08-18 00:31:28 阅读量: 1 订阅数: 3 

# SML编程:从基础声明到高阶函数
## 1. 命名规则与保留字
在SML编程中,有一些命名规则和特殊的保留字需要我们了解。
### 1.1 命名约定
- 与实数相关的名称,可在名称前后加 `r`。
- 与字符串相关的名称,可在名称前后加 `s`,如 `s s1 s2 s3 …`。
- 与任意值相关的名称,使用 `v v1 v2 v3 …`。
- 与任意列表相关的名称,使用 `1 11 12 13 …`。
### 1.2 保留字
SML中有许多具有特殊意义的名称,被称为保留字,例如:
```plaintext
abstype and andalso as case do datatype else end eqtype exception fn fun functor handle if in include infix infixr
let local nonfix of op open orelse raise rec sharing sig signature struct structure then type val with withtype while
```
这些保留字不能在程序中用作名称,因为系统会默认它们具有SML的特殊意义。
## 2. 全局声明
全局声明用于在SML会话期间将名称与值关联起来,其形式为:
```plaintext
val name = expression
```
系统会计算表达式的值,并将名称与该值关联起来,然后输出结果:
```plaintext
> val name = value : type
```
以下是一些示例:
```plaintext
– val pay = 12000;
> val pay = 12000 : int
– val name = ("Dennis", "Menace");
> val name = ("Dennis", "Menace") : string * string
```
全局声明的名称在后续使用时会返回关联的值,并且可以在表达式中替代常量使用。例如:
```plaintext
– pay−4000;
> 8000 : int
– val tax = pay * 25 div 100;
> val tax = 3000 : int
– val payslip = (name, pay, tax, pay-tax);
> val payslip =
(("Dennis", "Menace"), 12000, 3000, 9000) :
(string * string) * int * int * int
```
一个典型的SML程序由一系列全局声明和使用这些声明的表达式组成。
## 3. 函数基础
### 3.1 函数定义与抽象
函数用于对表达式进行抽象,其形式为:
```plaintext
fn name => expression
```
这里的 `name` 是形式参数,也称为绑定变量,`expression` 是函数体。如果 `name` 可以关联类型为 `type1` 的值,而表达式返回类型为 `type2` 的值,那么函数的类型为:
```plaintext
type1 -> type2
```
这意味着函数是从类型 `type1` 的定义域到类型 `type2` 的值域的映射。
### 3.2 函数类型推导
SML系统通常可以从函数体中绑定变量的使用方式推导出其类型。例如,计算25%所得税的函数:
```plaintext
– fn sum => sum*25 div 100;
> fn : int -> int
```
系统根据 `*` 运算符的使用,推断出 `sum` 必须是整数,因此函数的定义域和值域都是整数。
### 3.3 函数调用
函数调用的形式为:
```plaintext
function_expression argument_expression
```
具体步骤如下:
1. 计算 `function_expression` 得到函数值。
2. 计算 `argument_expression` 得到值,该值的类型必须与函数的定义域类型相同。
3. 将函数体中绑定变量的所有出现替换为参数值,然后计算函数体得到结果值。
以下是一些函数调用的示例:
```plaintext
– (fn sum => sum*25 div 100) 10000;
> 2500 : int
– (fn sum => sum*25 div 100) 12000;
> 3000 : int
– (fn word => word^"s") "banana";
> "bananas" : string
– (fn word => word^"s") "fishcake";
> "fishcakes" : string
– (fn age=>age>=18) 17;
> false : bool
```
### 3.4 函数调用流程图
```mermaid
graph TD;
A[开始] --> B[计算function_expression];
B --> C[得到函数值];
C --> D[计算argument_expression];
D --> E[得到参数值];
E --> F{参数值类型是否与定义域类型相同};
F -- 是 --> G[替换绑定变量];
F -- 否 --> H[出错];
G --> I[计算函数体];
I --> J[得到结果值];
J --> K[结束];
H --> K;
```
## 4. 函数命名与注释
### 4.1 函数
0
0
复制全文
相关推荐









