Bend/docs/defining-data-types.md

53 lines
1.4 KiB
Markdown
Raw Normal View History

# Defining data types
2024-05-22 18:01:03 +03:00
It is possible to easily define complex data types using the `type` keyword.
2024-05-20 20:10:36 +03:00
```py
# A Boolean is either True or False
2024-05-22 18:01:03 +03:00
type Bool = True | False
```
If a constructor has any arguments, parentheses are necessary around it:
2024-05-20 20:10:36 +03:00
```py
# An option either contains some value, or None
2024-05-22 18:01:03 +03:00
type Option = (Some val) | None
```
If the data type has a single constructor, it can be destructured using `let`:
2024-05-20 20:10:36 +03:00
```py
# A Box is a wrapper around a value.
2024-05-22 18:01:03 +03:00
type Boxed = (Box val)
let (Box value) = boxed; value
```
The fields of the constructor that is being destructured with the `match` are bound to the matched variable plus `.` and the field names.
2024-05-20 20:10:36 +03:00
```py
Option.map = λoption λf
match option {
Some: (Some (f option.val))
None: None
}
```
Rules can also have patterns.
They work like match expressions with explicit bindings:
2024-05-20 20:10:36 +03:00
```py
(Option.map (Some value) f) = (Some (f value))
(Option.map None f) = None
```
However, they also allow matching on multiple values at once, which is something that regular `match` can't do:
2024-05-20 20:10:36 +03:00
```py
2024-05-22 18:59:49 +03:00
type Boolean = True | False
(Option.is_both_some (Some lft_val) (Some rgt_val)) = True
(Option.is_both_some lft rgt) = False
```
2024-05-18 00:11:27 +03:00
You can read more about pattern matching rules in [Pattern matching](/docs/pattern-matching.md).
2024-05-22 18:01:03 +03:00
In conclusion, the `type` keyword is very useful as it allows you to easily create data types and deconstruct them.