Skip to content

Commit

Permalink
Add stdlib function array.at_or
Browse files Browse the repository at this point in the history
This is to return value at given position of array or default in case
provided position is out of bound.
  • Loading branch information
olorin37 committed May 28, 2024
1 parent ca0f78f commit 51ba172
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ expression: err
---
error: contract broken by the caller of `range`
invalid range
┌─ <stdlib/std.ncl>:649:9
┌─ <stdlib/std.ncl>:672:9
649| std.contract.unstable.RangeFun Dyn
672| std.contract.unstable.RangeFun Dyn
---------------------------------- expected type
┌─ [INPUTS_PATH]/errors/array_range_reversed_indices.ncl:3:19
Expand All @@ -21,5 +21,3 @@ note:
3std.array.range 1 0
------------------- (1) calling range


Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ expression: err
---
error: contract broken by the caller of `range_step`
invalid range step
┌─ <stdlib/std.ncl>:624:9
┌─ <stdlib/std.ncl>:647:9
624| std.contract.unstable.RangeFun (std.contract.unstable.RangeStep -> Dyn)
647| std.contract.unstable.RangeFun (std.contract.unstable.RangeStep -> Dyn)
----------------------------------------------------------------------- expected type
┌─ [INPUTS_PATH]/errors/array_range_step_negative_step.ncl:3:27
Expand All @@ -26,5 +26,3 @@ note:
3 │ std.array.range_step 0 10 (-1)
│ ------------------------------ (1) calling range_step


23 changes: 23 additions & 0 deletions core/stdlib/std.ncl
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,29 @@
"%
= fun n l => %elem_at% l n,

at_or
: forall a. Number -> a -> Array a -> a
| std.number.Nat -> Dyn
| doc m%"
Retrieves the n-th element from an array, with indices starting at 0
or provided value in case index is out of bounds.

# Examples

```nickel
std.array.at_or 3 "default" [ "zero", "one", "two", "three" ] =>
"three"

std.array.at_or 3 "default" [ "zero", "one" ] =>
"default"
```
"%
= fun n default_value array =>
if n < %length% array then
%elem_at% array n
else
default_value,

concat
: forall a. Array a -> Array a -> Array a
| doc m%"
Expand Down

0 comments on commit 51ba172

Please sign in to comment.