Gleam 中有两种不同的数字:整数和浮点数。
整数是不带小数的数。
let integer = 3
// -> 3
Gleam 提供了多个可用于整数的运算符。
1 + 1 // -> 2
5 - 1 // -> 4
5 / 2 // -> 2
3 * 3 // -> 9
5 % 2 // -> 1
2 > 1 // -> True
2 < 1 // -> False
2 >= 1 // -> True
2 <= 1 // -> False
浮点数的小数点后有一位或多位数字。
let float = 3.45
// -> 3.45
浮点数也有自己的一套运算符。
1.0 +. 1.4 // -> 2.4
5.0 -. 1.5 // -> 3.5
5.0 /. 2.0 // -> 2.5
3.0 *. 3.1 // -> 9.3
2.0 >. 1.0 // -> True
2.0 <. 1.0 // -> False
2.0 >=. 1.0 // -> True
2.0 <=. 1.0 // -> False
Gleam 代码按模块来组织,每个文件就是一个 Gleam 模块。
到目前为止,我们一直用 pub fn 语法来写函数,它定义的函数对其他模块公开可用。用 fn 定义的函数则只对它所在的模块私有,其他模块无法使用。
// This function is public
pub fn add(x, y) {
x + y
}
// This function is private
fn subtract(x, y) {
x - y
}
Gleam 模块有名称,名称取决于它在 src 或 test 目录下的文件路径。
例如,定义在 src\geometry\rectangle.gleam(Windows)或 src/geometry/rectangle.gleam(类 UNIX 操作系统)中的模块,名称为geometry/rectangle。
要访问其他模块中定义的函数,需要通过导入来完成。导入某个模块时,该模块公开的所有函数都会变得可以访问。但访问它们的方式取决于模块是怎么导入的。
限定导入是默认方式,访问这类模块中的函数(例如gleam/list模块中的map函数)时,要在前面加上模块名(list.map)。
// Import the int module
import gleam/int
pub fn run(x: Int) -> String {
// Use the to_string function from the int module
int.to_string(x)
}
默认情况下,用来指代模块的名称是模块名的最后一部分,在这里是int,不过可以用 as 关键字来改变。
// Import the int module and refer to it as i
import gleam/int as i
pub fn run(x: Int) -> String {
i.to_string(x)
}
非限定导入可以直接访问模块里公开的函数,无需添加前缀。
// Import the to_string function from the int module
import gleam/int.{to_string}
pub fn run(x: Int) -> String {
to_string(x)
}
推荐使用限定导入,因为它能让读者更清楚地看出函数来自哪里,也能避免名称冲突。
Gleam 有一个丰富且文档完善的标准库。文档可以在线查阅:hexdocs.pm/gleam_stdlib。把这个链接保存好,你会经常用到它!
大多数内置数据类型都有对应的模块,提供处理该数据类型的函数,例如整数有 gleam/int 模块,字符串有 gleam/string 模块,数组有 gleam/list 模块,等等。
在这个练习中,你将编写一些代码来帮助 Betty's Bike Shop,一家销售自行车和配件的网店。 你有三个任务,目标是在网站上正确显示自行车和配件的价格。
pence_to_pounds函数你的同事已经写好了这个模块的骨架,也就是尚未完成的函数pence_to_pounds和pounds_to_string。
不过,他们忘记导出pence_to_pounds函数,所以目前其他模块和测试套件都看不到它。
导出pence_to_pounds函数。
目前,价格以整数个便士存储(这家自行车店位于英国)。
在网站上,我们希望以英镑显示价格,其中 1.00 英镑等于 100 便士。
你的第一个任务是实现pence_to_pounds函数,它接收一个以Int表示的便士金额,并把它转换成等值的英镑,结果为Float。
你还应该为这个函数添加类型注解。
pence_to_pounds(106)
// -> 1.06
由于 Betty's 的自行车以英镑出售,价格显示时应该带上符号“£”。
因此,你的第二个任务是实现pounds_to_string函数,它接收一个以Float表示的英镑金额,并返回显示为String的价格,前面加上英镑符号。
在使用gleam/float和gleam/string模块之前,你应该先导入它们。
你还应该为pounds_to_string定义类型注解。
pounds_to_string(1.06)
// -> "£1.06"