From 39d5b221f7c28e76262fc7e8b0746152a46c97c5 Mon Sep 17 00:00:00 2001 From: Ivan Habunek Date: Thu, 8 Dec 2022 17:48:20 +0100 Subject: Make list.at return an error given sub-zero index --- CHANGELOG.md | 2 ++ src/gleam/list.gleam | 15 +++++++++------ test/gleam/list_test.gleam | 2 +- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d921c6f..83b76ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ - The `io.debug` function now prints to stderr instead of stdout when using the Erlang target or running in Node.js (but still uses `console.log` when running as JavaScript in a browser) +- The `list.at` function now returns `Error(Nil)` if given index is smaller than + zero, instead of returning the first element. ## v0.25.0 - 2022-11-19 diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam index 3f5f566..0fad104 100644 --- a/src/gleam/list.gleam +++ b/src/gleam/list.gleam @@ -1036,9 +1036,8 @@ pub fn intersperse(list: List(a), with elem: a) -> List(a) { /// Returns the element in the Nth position in the list, with 0 being the first /// position. /// -/// `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. +/// `Error(Nil)` is returned if the list is not long enough for the given index +/// or if the index is less than 0. /// /// ## Examples /// @@ -1053,9 +1052,13 @@ pub fn intersperse(list: List(a), with elem: a) -> List(a) { /// ``` /// pub fn at(in list: List(a), get index: Int) -> Result(a, Nil) { - list - |> drop(index) - |> first + case index >= 0 { + True -> + list + |> drop(index) + |> first + False -> Error(Nil) + } } /// Removes any duplicate elements from a given list. diff --git a/test/gleam/list_test.gleam b/test/gleam/list_test.gleam index d09dfc0..ce865e4 100644 --- a/test/gleam/list_test.gleam +++ b/test/gleam/list_test.gleam @@ -537,7 +537,7 @@ pub fn at_test() { |> should.equal(Error(Nil)) list.at([1, 2, 3, 4, 5, 6], -1) - |> should.equal(Ok(1)) + |> should.equal(Error(Nil)) } pub fn unique_test() { -- cgit v1.2.3