More efficient way to update an item in a list in Elm?

Is there a more efficient way to update an item in a list in Elm than mapfor each item?

{ model | items = List.indexedMap (\i x -> if i == 2 then "z" else x) model.items }

Maybe the Elm compiler is sophisticated enough to optimize this so that mapor indexedMapnot over-copy every element except 1. What about nested lists?

Clojure hasassoc-in to update an item inside a nested list or entry (can also be combined). Does Elm have an equivalent?

+4
source share
4 answers

More efficient in terms of the amount of code would be (this is similar to @MichaelKohl's answer):

List.take n list ++ newN :: List.drop (n+1) list

PS: n < 0 n > ( - 1), .

PPS: , , a :: alist , [a] ++ alist.

/ :

, Array ( Dict) .

:

  • Array Dict /, // .
  • List , , .

List view. ( update) Dict Array .

+2

Elm, , , , , , .

, , , , - ( List.concat):

List.take n list ++ newN :: List.drop (n+1) 

/ .

+1

, . Array. Array set, . :

import Html exposing (text)
import Array

type alias Model = { items : Array.Array String }

model =
  { items = Array.fromList ["a", "b", "c"]
  }

main =
  let 
    m = { model | items = Array.set 2 "z" model.items }
    z = Array.get 2 m.items
    output = case z of
      Just n -> n
      Nothing -> "Nothing"
  in
    text output -- The output will be "z"

- model.items List, , Array List.

+1

, Elm List .

. . , , - . ( , , , , , . , .)

updateListAt :: List a -> Int -> a -> List a
updateListAt (head :: tail) 0 x = x :: tail
updateListAt (head :: tail) i x = head :: (updateListAt tail (i - 1) x)

However, both the runtime and the complexity of the space will be O (n) both on average and in the worst case, regardless of the method used. This is due to the fact that Elm Listis a singly linked list.

Relatively assoc-in, if you look at the source of Clojure, you will see that it is assoc-insimply recursively defined in terms assoc. However, I think you will have trouble entering it for an arbitrary dynamic depth in Elm.

0
source

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


All Articles