Skip to content

Commit cfeac97

Browse files
authored
Make array_first and array_shift failable when the array is empty (#789)
1 parent eeb5c5c commit cfeac97

File tree

3 files changed

+19
-9
lines changed

3 files changed

+19
-9
lines changed

src/std/array.ab

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff 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.
3232
pub 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.
7981
pub 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

src/tests/stdlib/array_first.ab

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff 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

77
fun 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

1215
main {
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
}

src/tests/stdlib/array_shift.ab

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff 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

77
fun 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

0 commit comments

Comments
 (0)