File tree Expand file tree Collapse file tree 3 files changed +19
-9
lines changed
Expand file tree Collapse file tree 3 files changed +19
-9
lines changed Original file line number Diff line number Diff line change @@ -27,9 +27,11 @@ pub fun array_contains(array, value) {
2727 return result >= 0
2828}
2929
30- /// Returns the first element in the array; if the array is empty, the return
31- /// value is undefined .
30+ /// Returns the first element in the array; if the array is empty, the function
31+ /// fails .
3232pub fun array_first(array) {
33+ if len(array) == 0:
34+ fail 1
3335 return array[0]
3436}
3537
@@ -75,9 +77,11 @@ pub fun array_pop(ref array) {
7577}
7678
7779/// Removes the first element from the array, and returns it; if the array
78- /// is empty, the return value is undefined, but the array will be unchanged.
80+ /// is empty, the function fails, and the array will be unchanged.
7981pub fun array_shift(ref array) {
8082 let length = len(array)
83+ if length == 0:
84+ fail 1
8185 let element = array[0]
8286 array = array[1..length]
8387 return element
Original file line number Diff line number Diff line change @@ -2,16 +2,19 @@ import { array_first } from "std/array"
22
33// Output
44// First of numbers: "zero" (4) [zero one two three]
5- // First of empty: "" (0) []
5+ // First of empty array does not exist
66
77fun test_first(label: Text, data: [Text]): Null {
8- let value = array_first(data)
8+ let value = array_first(data) failed {
9+ echo "First of empty array does not exist"
10+ return null
11+ }
912 echo "First of {label}: \"{value}\" ({len(data)}) [{data}]"
1013}
1114
1215main {
1316 let numbers = ["zero", "one", "two", "three"]
1417 let empty = [Text]
15- test_first("numbers", numbers)
16- test_first("empty", empty)
18+ test_first("numbers", numbers)?
19+ test_first("empty", empty)?
1720}
Original file line number Diff line number Diff line change @@ -2,10 +2,13 @@ import { array_shift } from "std/array"
22
33// Output
44// Shifted from numbers: "zero" (3) [one two three]
5- // Shifted from empty: "" (0) []
5+ // First of empty array does not exist
66
77fun test_shift(label: Text, data: [Text]): Null {
8- let value = array_shift(data)
8+ let value = array_shift(data) failed {
9+ echo "First of empty array does not exist"
10+ return null
11+ }
912 echo "Shifted from {label}: \"{value}\" ({len(data)}) [{data}]"
1013}
1114
You can’t perform that action at this time.
0 commit comments