Replace individual list elements in Haskell?

后端 未结 9 683
死守一世寂寞
死守一世寂寞 2020-12-01 12:02

I have a list of elements and I wish to update them:

from this: [\"Off\",\"Off\",\"Off\",\"Off\"]

to this: [\"Off\",\"Off\",\"On\",\"Off\

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 12:28

    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.

提交回复
热议问题