Skip to content

Commit

Permalink
Note that ranges can be cast into an array (#795)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dhghomon authored Aug 29, 2024
1 parent f495af5 commit f55a7ad
Showing 1 changed file with 41 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,45 @@ FOR $year IN 0..=2024 {
for_year = $year,
events = "To be added";
}
```

## Casting and functional usage

A range can be cast into an array.

```surql
<array>1..3;
```

```bash title="Output"
[
1,
2
]
```

This opens up a range of functional programming patterns that are made possible by SurrealDB's [array functions](/docs/surrealdb/surrealql/functions/database/array), many of which can use [anonymous functions](/docs/surrealdb/surrealql/datamodel/closures) (closures) to perform an operation on each item in the array.

```surql
-- Construct an array
(<array>1..=100)
-- Turn it into an array that increments by 10
.map(|$v| $v * 10)
-- Turn each number into a object with original and square root value
.map(|$v| { original: $v, square_root: math::sqrt($v) })
-- Keep only those with square roots in between 11 and 12
.filter(|$obj| $obj.square_root IN 11..12);
```

```bash title="Output"
[
{
original: 130,
square_root: 11.40175425099138f
},
{
original: 140,
square_root: 11.832159566199232f
}
]
```

0 comments on commit f55a7ad

Please sign in to comment.