Merge pull request #300 from erdeszt/list-init

Add init function
This commit is contained in:
Evan Czaplicki 2013-10-18 09:08:49 -07:00
commit 464c4e8256
2 changed files with 21 additions and 1 deletions

View file

@ -7,7 +7,7 @@ list must have the same type.
@docs (::), (++), isEmpty, length, reverse, map
# Sub-lists
@docs head, tail, last, filter, take, drop
@docs head, tail, last, init, filter, take, drop
# Putting Lists Together
@docs concat, concatMap, join, intersperse, zip, zipWith
@ -58,6 +58,12 @@ tail = Native.List.tail
last : [a] -> a
last = Native.List.last
{-| Extract the elements before the last element in the list. List must be non-empty.
`(init [1,2,3] == [1,2])
-}
init : [a] -> [a]
init = Native.List.init
{-| Check if a list is empty `(isEmpty [] == True)` -}
isEmpty : [a] -> Bool
isEmpty xs =

View file

@ -81,6 +81,19 @@ Elm.Native.List.make = function(elm) {
return out;
}
function init(xs) {
if (xs.ctor === '[]') { throwError('init'); }
var root = Cons(xs._0, Nil);
var curr = root;
xs = xs._1;
while (xs._1.ctor !== '[]') {
curr._1 = Cons(xs._0, Nil)
xs = xs._1
curr = curr._1
}
return root;
}
function map(f, xs) {
var arr = [];
while (xs.ctor !== '[]') {
@ -278,6 +291,7 @@ Elm.Native.List.make = function(elm) {
head:head,
tail:tail,
last:last,
init:init,
map:F2(map),
foldl:F3(foldl),