如何从Elm中的Array / List中删除给定索引处的项目?

时间:2015-10-13 10:10:33

标签: arrays list elm

在给定i中删除索引Array处的项目的最优雅方法是什么?在给定的List

6 个答案:

答案 0 :(得分:15)

我能想到的最好:

removeFromList i xs =
  (List.take i xs) ++ (List.drop (i+1) xs) 

removeFromArray i =
  Array.toList >> removeFromList i >> Array.fromList 

答案 1 :(得分:3)

使用elm-community中的List.Extra.removeAt

答案 2 :(得分:2)

我最近需要一个indexedFilter功能。这可以为您提供基于折叠的替代

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

答案 3 :(得分:2)

这是基于J from的另一种解决方案。

用法:

[-1,2,0] `from` ["fran","world","san","hello"]

返回:[Just "hello",Just "san",Just "fran"]

定义,在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)
    _ -> []

答案 4 :(得分:2)

这应该非常有效:

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

答案 5 :(得分:0)

“ elm-community / array-extra”软件包现在提供此功能:

https://package.elm-lang.org/packages/elm-community/array-extra/2.1.0/Array-Extra#removeAt