Reputation: 171351
What is the most elegant way to remove an item at index i
in a given Array
? In a given List
?
Upvotes: 10
Views: 4311
Reputation: 43310
The "elm-community/array-extra" package now provides this function:
https://package.elm-lang.org/packages/elm-community/array-extra/2.1.0/Array-Extra#removeAt
Upvotes: 0
Reputation: 2582
This should be pretty efficient:
remove : Int -> Array a -> Array a
remove i a =
let
a1 = Array.slice 0 i a
a2 = Array.slice (i+1) (Array.length a) a
in
Array.append a1 a2
Upvotes: 7
Reputation: 3829
Here's a different kind of solution based on J's from
.
Usage:
[-1,2,0] `from` ["fran","world","san","hello"]
which returns: [Just "hello",Just "san",Just "fran"]
Definition, after import List exposing (..)
:
get idx lst = -- get an element from a list (negative indexes from end)
if idx >= 0 then
head (drop idx lst)
else
head (drop (negate (idx+1)) (reverse lst))
from idxs lst = -- atoms of idxs are indexes into lst
case idxs of
hd::tl -> (get hd lst)::(from tl lst)
_ -> []
Upvotes: 2
Reputation: 21005
I needed an indexedFilter
function recently. This could provide you a fold based alternative
indexedFilter : (Int -> a -> Bool) -> List a -> List a
indexedFilter p xs =
let
tup = List.map2 (,) [ 0 .. List.length xs - 1 ] xs
in List.foldr (\(i,x) acc -> if p i x then x :: acc else acc) [] tup
Upvotes: 2
Reputation: 2923
Best I could think of:
removeFromList i xs =
(List.take i xs) ++ (List.drop (i+1) xs)
removeFromArray i =
Array.toList >> removeFromList i >> Array.fromList
Upvotes: 18