How to remove an element at a given index from an array / list in Elm?

What is the most elegant way to delete an element at index i in a given Array ? In this List ?

+5
source share
5 answers

The 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 
+11
source

I needed an indexedFilter function. This may provide you with a crease-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 pix then x :: acc else acc) [] tup 
+2
source

A different kind of solution is used here, based on J from .

Using:

 [-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) _ -> [] 
+2
source

This should be pretty effective:

 remove : Int -> Array a -> Array a remove ia = let a1 = Array.slice 0 ia a2 = Array.slice (i+1) (Array.length a) a in Array.append a1 a2 
+1
source

Use List.Extra.removeAt from elm-community .

+1
source

Source: https://habr.com/ru/post/1233599/


All Articles