I have a list of elements and I wish to update them:
from this: [\"Off\",\"Off\",\"Off\",\"Off\"]
to this: [\"Off\",\"Off\",\"On\",\"Off\
This answer arrives quite late, but I thought I'd share what I think is an efficient way of replacing the nth element in a list in Haskell. I'm new to Haskell and thought I'd pitch in.
The set function sets the nth element in a list to a given value:
set' :: Int -> Int -> a -> [a] -> [a]
set' _ _ _ [] = []
set' ind curr new arr@(x:xs)
| curr > ind = arr
| ind == curr = new:(set' ind (curr+1) new xs)
| otherwise = x:(set' ind (curr+1) new xs)
set :: Int -> a -> [a] -> [a]
set ind new arr = (set' ind 0 new arr)
As set traverses a list, it breaks the list apart and if the current index is the given n it combines the previous element with the given new value, otherwise, it combines the previous element with the old value in the list for that index.