mirror of
https://github.com/erg-lang/erg.git
synced 2025-09-30 21:01:10 +00:00

Some additional modifications - Fix typing errors to English instead of Japanese - Update hash value - Additional translation - コメント内のですます調をだ、である調に変更した - "可能"と"できる"が混ざっていたためこれらを"できる"に統一した
44 lines
1.6 KiB
Markdown
44 lines
1.6 KiB
Markdown
# 展開代入
|
|
|
|
[](https://gezf7g7pd5.execute-api.ap-northeast-1.amazonaws.com/default/source_up_to_date?owner=erg-lang&repos=erg&ref=main&path=doc/EN/syntax/28_spread_syntax.md&commit_hash=06f8edc9e2c0cee34f6396fd7c64ec834ffb5352)
|
|
|
|
分解代入において、変数の前に`...`を置くと残りの要素を全てその変数に展開できます。これを展開代入と呼びます。
|
|
|
|
```python
|
|
[x, ...y] = [1, 2, 3]
|
|
assert x == 1
|
|
assert y == [2, 3]
|
|
x, ...y = (1, 2, 3)
|
|
assert x == 1
|
|
assert y == (2, 3)
|
|
```
|
|
|
|
## 抽出代入
|
|
|
|
`...`のあとに何も書かない場合、残りの要素は無視して代入されます。このタイプの展開代入を特に抽出代入と呼びます。
|
|
抽出代入は、モジュールやレコード内にある特定の属性をローカルに持ってくる際に便利な構文です。
|
|
|
|
```python
|
|
{sin; cos; tan; ..} = import "math"
|
|
```
|
|
|
|
このようにすると、以降はローカルで`sin, cos, tan`が使用できます。
|
|
|
|
レコードでも同じようにできます。
|
|
|
|
```python
|
|
record = {x = 1; y = 2}
|
|
{x; y; ...} = record
|
|
```
|
|
|
|
全て展開したい場合は`{*} = record`とします。OCamlなどでいう`open`です。
|
|
|
|
```python
|
|
record = {x = 1; y = 2}
|
|
{*} = record
|
|
assert x == 1 and y == 2
|
|
```
|
|
|
|
<p align='center'>
|
|
<a href='./27_comprehension.md'>Previous</a> | <a href='./29_decorator.md'>Next</a>
|
|
</p>
|