aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--lib/stdlib/doc/src/lists.xml8
-rw-r--r--lib/stdlib/src/lists.erl15
-rw-r--r--lib/stdlib/test/lists_SUITE.erl12
3 files changed, 32 insertions, 3 deletions
diff --git a/lib/stdlib/doc/src/lists.xml b/lib/stdlib/doc/src/lists.xml
index 251a383cf8..ee3c51c62c 100644
--- a/lib/stdlib/doc/src/lists.xml
+++ b/lib/stdlib/doc/src/lists.xml
@@ -123,6 +123,14 @@
</desc>
</func>
<func>
+ <name name="droplast" arity="1"/>
+ <fsummary>Drop the last element of a list</fsummary>
+ <desc>
+ <p>Drops the last element of a <c><anno>List</anno></c>. The list should
+ be non-empty, otherwise the function will crash with a <c>function_clause</c></p>
+ </desc>
+ </func>
+ <func>
<name name="dropwhile" arity="2"/>
<fsummary>Drop elements from a list while a predicate is true</fsummary>
<desc>
diff --git a/lib/stdlib/src/lists.erl b/lib/stdlib/src/lists.erl
index d6a9f4645d..6303465d3d 100644
--- a/lib/stdlib/src/lists.erl
+++ b/lib/stdlib/src/lists.erl
@@ -22,7 +22,7 @@
-compile({no_auto_import,[min/2]}).
-export([append/2, append/1, subtract/2, reverse/1,
- nth/2, nthtail/2, prefix/2, suffix/2, last/1,
+ nth/2, nthtail/2, prefix/2, suffix/2, droplast/1, last/1,
seq/2, seq/3, sum/1, duplicate/2, min/1, max/1, sublist/2, sublist/3,
delete/2,
unzip/1, unzip3/1, zip/2, zip3/3, zipwith/3, zipwith3/4,
@@ -203,6 +203,19 @@ suffix(Suffix, List) ->
Delta = length(List) - length(Suffix),
Delta >= 0 andalso nthtail(Delta, List) =:= Suffix.
+%% droplast(List) returns the list dropping its last element
+
+-spec droplast(List) -> InitList when
+ List :: [T, ...],
+ InitList :: [T],
+ T :: term().
+
+%% This is the simple recursive implementation
+%% reverse(tl(reverse(L))) is faster on average,
+%% but creates more garbage.
+droplast([_T]) -> [];
+droplast([H|T]) -> [H|droplast(T)].
+
%% last(List) returns the last element in a list.
-spec last(List) -> Last when
diff --git a/lib/stdlib/test/lists_SUITE.erl b/lib/stdlib/test/lists_SUITE.erl
index 92253ef5b9..f4589a8e24 100644
--- a/lib/stdlib/test/lists_SUITE.erl
+++ b/lib/stdlib/test/lists_SUITE.erl
@@ -61,7 +61,7 @@
zip_unzip/1, zip_unzip3/1, zipwith/1, zipwith3/1,
filter_partition/1,
otp_5939/1, otp_6023/1, otp_6606/1, otp_7230/1,
- suffix/1, subtract/1]).
+ suffix/1, subtract/1, droplast/1]).
%% Sort randomized lists until stopped.
%%
@@ -2641,4 +2641,12 @@ sub_non_matching(A, B) ->
sub(A, B) ->
Res = A -- B,
Res = lists:subtract(A, B).
-
+
+%% Test lists:droplast/1
+droplast(Config) when is_list(Config) ->
+ ?line [] = lists:droplast([x]),
+ ?line [x] = lists:droplast([x, y]),
+ ?line {'EXIT', {function_clause, _}} = (catch lists:droplast([])),
+ ?line {'EXIT', {function_clause, _}} = (catch lists:droplast(x)),
+
+ ok.