Replace individual list elements in Haskell?

后端 未结 9 663
死守一世寂寞
死守一世寂寞 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条回答
  •  -上瘾入骨i
    2020-12-01 12:34

    Here's some code that I've been using:

    -- | Replaces an element in a list with a new element, if that element exists.
    safeReplaceElement
      -- | The list
      :: [a]
      -- | Index of the element to replace.
      -> Int
      -- | The new element.
      -> a
      -- | The updated list.
      -> [a]
    safeReplaceElement xs i x =
      if i >= 0 && i < length xs
        then replaceElement xs i x
        else xs
    
    
    -- | Replaces an element in a list with a new element.
    replaceElement
      -- | The list
      :: [a]
      -- | Index of the element to replace.
      -> Int
      -- | The new element.
      -> a
      -- | The updated list.
      -> [a]
    replaceElement xs i x = fore ++ (x : aft)
      where fore = take i xs
            aft = drop (i+1) xs
    

提交回复
热议问题