diff --git a/CHANGELOG.md b/CHANGELOG.md index b85320761..c0e341412 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,7 @@ also non string parameters (e.g. `Enum.join([1, 2], ",")` - Add support to Elixir for `Keyword.split/2` - Support for `binary:split/3` and `string:find/2,3` - Support for large tuples (more than 255 elements) in external terms. +- Support for `lists:nthtail/2` ### Changed diff --git a/libs/estdlib/src/lists.erl b/libs/estdlib/src/lists.erl index d02031f8e..9aecce834 100644 --- a/libs/estdlib/src/lists.erl +++ b/libs/estdlib/src/lists.erl @@ -32,6 +32,7 @@ -export([ map/2, nth/2, + nthtail/2, last/1, member/2, delete/2, @@ -92,6 +93,22 @@ nth(1, [H | _T]) -> nth(Index, [_H | T]) when Index > 1 -> nth(Index - 1, T). +%%----------------------------------------------------------------------------- +%% @param N the index to start the sublist from +%% @param L the list from which to extract a tail +%% @returns a sublist of list starting from position N. +%% @doc Get the sublist of list L starting after the element N. +%% +%% The behavior of this function is undefined if N is outside of the +%% {0..length(L)}. +%% @end +%%----------------------------------------------------------------------------- +-spec nthtail(N :: non_neg_integer(), L :: list()) -> list(). +nthtail(0, L) when is_list(L) -> + L; +nthtail(N, [_H | T]) when is_integer(N) andalso N > 0 -> + nthtail(N - 1, T). + %%----------------------------------------------------------------------------- %% @param L the proper list from which to get the last item %% @returns the last item of the list. diff --git a/tests/libs/estdlib/test_lists.erl b/tests/libs/estdlib/test_lists.erl index 133a33f2c..72dc3bf49 100644 --- a/tests/libs/estdlib/test_lists.erl +++ b/tests/libs/estdlib/test_lists.erl @@ -26,6 +26,7 @@ test() -> ok = test_nth(), + ok = test_nthtail(), ok = test_member(), ok = test_delete(), ok = test_keyfind(), @@ -57,6 +58,15 @@ test_nth() -> ?ASSERT_ERROR(lists:nth(-1, [a, b, c]), function_clause), ok. +test_nthtail() -> + ?ASSERT_MATCH(lists:nthtail(0, [a, b, c]), [a, b, c]), + ?ASSERT_MATCH(lists:nthtail(1, [a, b, c]), [b, c]), + ?ASSERT_MATCH(lists:nthtail(2, [a, b, c]), [c]), + ?ASSERT_MATCH(lists:nthtail(3, [a, b, c]), []), + ?ASSERT_ERROR(lists:nthtail(-1, [a, b, c]), function_clause), + ?ASSERT_ERROR(lists:nthtail(4, [a, b, c]), function_clause), + ok. + test_member() -> ?ASSERT_TRUE(lists:member(a, [a, b, c])), ?ASSERT_TRUE(lists:member(b, [a, b, c])),