on master help sign in
Merge pull request #300 from erdeszt/list-init

Add init function

commit464c4e82560f050bf4cb4edbf02fc35d9b670845 authorEvan Czaplicki <info@elm-lang.org> dateFri 18 Oct 2013, 09:08 (13 years ago) parent83406ff2ffacb7
2 files changed+21−1
libraries/List.elm+7−1 libraries/Native/List.js+14
libraries/List.elm+7−1
@@ -7,7 +7,7 @@ list must have the same type.
77@docs (::), (++), isEmpty, length, reverse, map
88
99# Sub-lists
10−@docs head, tail, last, filter, take, drop
10+@docs head, tail, last, init, filter, take, drop
1111
1212# Putting Lists Together
1313@docs concat, concatMap, join, intersperse, zip, zipWith
@@ -58,6 +58,12 @@ tail = Native.List.tail
5858last : [a] -> a
5959last = Native.List.last
6060
61+{-| Extract the elements before the last element in the list. List must be non-empty.
62+`(init [1,2,3] == [1,2])
63+-}
64+init : [a] -> [a]
65+init = Native.List.init
66+
6167{-| Check if a list is empty `(isEmpty [] == True)` -}
6268isEmpty : [a] -> Bool
6369isEmpty xs =
libraries/Native/List.js+14
@@ -81,6 +81,19 @@ Elm.Native.List.make = function(elm) {
8181 return out;
8282 }
8383
84+ function init(xs) {
85+ if (xs.ctor === '[]') { throwError('init'); }
86+ var root = Cons(xs._0, Nil);
87+ var curr = root;
88+ xs = xs._1;
89+ while (xs._1.ctor !== '[]') {
90+ curr._1 = Cons(xs._0, Nil)
91+ xs = xs._1
92+ curr = curr._1
93+ }
94+ return root;
95+ }
96+
8497 function map(f, xs) {
8598 var arr = [];
8699 while (xs.ctor !== '[]') {
@@ -278,6 +291,7 @@ Elm.Native.List.make = function(elm) {
278291 head:head,
279292 tail:tail,
280293 last:last,
294+ init:init,
281295
282296 map:F2(map),
283297 foldl:F3(foldl),