Skip to content

Commit

Permalink
add doc for map pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
Guest0x0 committed May 20, 2024
1 parent 3870c2e commit 7af4994
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,24 @@ match expr {
}
```

### Map Pattern
MoonBit allows convenient matching on map-like data structures:
```rust
match map {
// matches if any only if "b" exists in `map`
{ "b": Some(_) } => ..
// matches if and only if "b" does not exist in `map` and "a" exists in `map`.
// When matches, bind the value of "a" in `map` to `x`
{ "b": None, "a": Some(x) } => ..
// compiler reports missing case: { "b": None, "a": None }
}
```

- To match a data type `T` using map pattern, `T` must have a method `op_get(Self, K) -> Option[V]` for some type `K` and `V`.
- Currently, the key part of map pattern must be a constant
- Map patterns are always open: unmatched keys are silently ignored
- Map pattern will be compiled to efficient code: every key will be fetched at most once

## Generics

Generics are supported in top-level function and data type definitions. Type parameters can be introduced within square brackets. We can rewrite the aforementioned data type `List` to add a type parameter `T` to obtain a generic version of lists. We can then define generic functions over lists like `map` and `reduce`.
Expand Down
18 changes: 18 additions & 0 deletions zh-docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -840,6 +840,24 @@ match expr {
}
```

### 键值对模式匹配
MoonBit 允许模式匹配字典等具有键值对结构的数据结构:
```rust
match map {
// 匹配键 "b" 存在的情况
{ "b": Some(_) } => ..
// 匹配 "b" 不存在且 "a" 存在的情况,
// 匹配成功时,把 "a" 的值绑定到 `x`
{ "b": None, "a": Some(x) } => ..
// 编译器指出下列情况没有被匹配到:{ "b": None, "a": None }
}
```

- 如果要用字典模式匹配类型 `T`,必须给类型 `T` 实现方法 `op_get``op_get` 的类型必须是 `(Self, K) -> Option[V]`,其中 `K` 是键的类型,`V` 是值的类型
- 目前,字典模式的键部分必须是一个常量
- 字典模式永远是开放的:未被匹配到的键会被忽略
- 字典模式会被编译成高效的代码:每个键至多被查询一次

## 泛型

您可以在顶层的函数和数据结构定义中使用泛型。类型参数可以由方括号引入。
Expand Down

0 comments on commit 7af4994

Please sign in to comment.