2024-01-08 23:44:03 +03:00
|
|
|
# Defining data types
|
|
|
|
|
2024-01-09 22:46:49 +03:00
|
|
|
It is possible to easily define complex data types using the `data` keyword.
|
2024-01-08 23:44:03 +03:00
|
|
|
|
2024-05-20 20:10:36 +03:00
|
|
|
```py
|
|
|
|
# A Boolean is either True or False
|
2024-01-08 23:44:03 +03:00
|
|
|
data 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-01-08 23:44:03 +03:00
|
|
|
data 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-01-08 23:44:03 +03:00
|
|
|
data Boxed = (Box val)
|
|
|
|
|
|
|
|
let (Box value) = boxed; value
|
|
|
|
```
|
|
|
|
|
2024-03-29 12:43:47 +03:00
|
|
|
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
|
2024-01-08 23:44:03 +03:00
|
|
|
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
|
2024-01-08 23:44:03 +03:00
|
|
|
(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-01-08 23:44:03 +03:00
|
|
|
data 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-03-29 12:43:47 +03:00
|
|
|
|
2024-05-18 00:11:06 +03:00
|
|
|
In conclusion, the `data` keyword is very useful as it allows you to easily create data types and deconstruct them.
|