on master help sign in
Add init function
2ffacb7erdeszt
libraries/List.elm+7−1
@@ -7,7 +7,7 @@ list must have the same type.
7@docs (::), (++), isEmpty, length, reverse, map
7@docs (::), (++), isEmpty, length, reverse, map
8
8
9# Sub-lists
9# Sub-lists
10−@docs head, tail, last, filter, take, drop
10+@docs head, tail, last, init, filter, take, drop
11
11
12# Putting Lists Together
12# Putting Lists Together
13@docs concat, concatMap, join, intersperse, zip, zipWith
13@docs concat, concatMap, join, intersperse, zip, zipWith
@@ -58,6 +58,12 @@ tail = Native.List.tail
58last : [a] -> a
58last : [a] -> a
59last = Native.List.last
59last = Native.List.last
60
60
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+
61{-| Check if a list is empty `(isEmpty [] == True)` -}
67{-| Check if a list is empty `(isEmpty [] == True)` -}
62isEmpty : [a] -> Bool
68isEmpty : [a] -> Bool
63isEmpty xs =
69isEmpty xs =
libraries/Native/List.js+14
@@ -81,6 +81,19 @@ Elm.Native.List.make = function(elm) {
81 return out;
81 return out;
82 }
82 }
83
83
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+
84 function map(f, xs) {
97 function map(f, xs) {
85 var arr = [];
98 var arr = [];
86 while (xs.ctor !== '[]') {
99 while (xs.ctor !== '[]') {
@@ -278,6 +291,7 @@ Elm.Native.List.make = function(elm) {
278 head:head,
291 head:head,
279 tail:tail,
292 tail:tail,
280 last:last,
293 last:last,
294+ init:init,
281
295
282 map:F2(map),
296 map:F2(map),
283 foldl:F3(foldl),
297 foldl:F3(foldl),