aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMarcin Puc <marcin.e.puc@gmail.com>2021-10-13 10:32:31 +0200
committerLouis Pilfold <louis@lpil.uk>2021-11-06 16:20:50 +0000
commitb99ec496f77d3c20b256a2da1922ed308d83fcbe (patch)
tree791248f0ba1e145724f9163ced17e2e760eb8b6a
parent007ef7ed3fad0f799f626af34642cc648791d332 (diff)
downloadgleam_stdlib-b99ec496f77d3c20b256a2da1922ed308d83fcbe.tar.gz
gleam_stdlib-b99ec496f77d3c20b256a2da1922ed308d83fcbe.zip
Simplify list.at implementation
-rw-r--r--src/gleam/list.gleam17
-rw-r--r--test/gleam/list_test.gleam2
2 files changed, 6 insertions, 13 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam
index 6278c6e..07a6953 100644
--- a/src/gleam/list.gleam
+++ b/src/gleam/list.gleam
@@ -882,6 +882,8 @@ pub fn intersperse(list: List(a), with elem: a) -> List(a) {
///
/// Error(Nil) is returned if the list is not long enough for the given index.
///
+/// For any `index` less than 0 this function behaves as if it was set to 0.
+///
/// ## Examples
///
/// > at([1, 2, 3], 1)
@@ -891,18 +893,9 @@ pub fn intersperse(list: List(a), with elem: a) -> List(a) {
/// Error(Nil)
///
pub fn at(in list: List(a), get index: Int) -> Result(a, Nil) {
- case index < 0 {
- True -> Error(Nil)
- False ->
- case list {
- [] -> Error(Nil)
- [x, ..rest] ->
- case index == 0 {
- True -> Ok(x)
- False -> at(rest, index - 1)
- }
- }
- }
+ list
+ |> drop(index)
+ |> first
}
/// Removes any duplicate elements from a given list.
diff --git a/test/gleam/list_test.gleam b/test/gleam/list_test.gleam
index b7275e4..8fc641a 100644
--- a/test/gleam/list_test.gleam
+++ b/test/gleam/list_test.gleam
@@ -376,7 +376,7 @@ pub fn at_test() {
|> should.equal(Error(Nil))
list.at([1, 2, 3, 4, 5, 6], -1)
- |> should.equal(Error(Nil))
+ |> should.equal(Ok(1))
}
pub fn unique_test() {