replaceElem.hs

Haskell

Public Domain

Change one or more elements of a list

Download (right click, save as, rename as appropriate)

Embed

1
2
3
4
5
6
7
8
replaceElem :: [a] -> Int -> a -> [a]
replaceElem list i new
 | 0 <= i && i <= length list = concat [(take i list), [new], (drop (i+1) list)]
 -- The ``i <= length list'' allows one to "replace" the element after the end
 -- of the list, thereby appending a new element.

replaceElems :: [a] -> [(Int, a)] -> [a]
replaceElems = foldl (\li (i, n) -> replaceElem li i n)