aboutsummaryrefslogtreecommitdiffstats
path: root/lib/stdlib/src
diff options
context:
space:
mode:
authorHans Svensson <[email protected]>2014-01-22 22:08:51 +0100
committerHans Svensson <[email protected]>2014-01-24 19:27:16 +0100
commit8c4f797785a8510e5662a27bfcb7359d32491de7 (patch)
tree6f0415cb89c15bc8555b67faeacabed3e839b1f0 /lib/stdlib/src
parent25237481ccccd3ddfa74582dc267632ad618ba30 (diff)
downloadotp-8c4f797785a8510e5662a27bfcb7359d32491de7.tar.gz
otp-8c4f797785a8510e5662a27bfcb7359d32491de7.tar.bz2
otp-8c4f797785a8510e5662a27bfcb7359d32491de7.zip
stdlib/lists: Add function droplast/1
This functions drops the last element of a non-empty list. lists:last/1 and lists:droplast/1 are the dual of hd/1 and tl/1 but for the end of a list.
Diffstat (limited to 'lib/stdlib/src')
-rw-r--r--lib/stdlib/src/lists.erl15
1 files changed, 14 insertions, 1 deletions
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