Replace individual list elements in Haskell?

后端 未结 9 639
死守一世寂寞
死守一世寂寞 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:26

    Actually, for many cases (not always) where you'd use a List, a Data.Vector is a better choice.

    It comes with an update function, see Hackage, that does exactly what you need.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-01 12:29

    I believe this is more elegant way of replacing an individual element:

    setelt:: Int -> [a] -> a -> [a]
    
    setelt i list newValue = 
      let (ys,zs) = splitAt i-1 list in  ys ++ newValue ++ tail zs
    

    There is input error handling. So if index i is out of boundaries haskell will show wrong output. (Note: in Haskell indexing starts from 1 onwards)

    Hugs would behave as follows:

    Main> setelt 1 [1,2,3] 9
    [9,2,3]
    Main> setelt 3 [1,2,3] 9
    [1,2,9]
    Main> setelt 0 [1,2,3] 9
    [9,2,3]
    Main> setelt 4 [1,2,3] 9
    [1,2,3,9]
    Program error: pattern match failure: tail []
    

    Error handling at your service:

    setelt i y newValue = 
        if and [i>0, i<= length y]
        then let (ys,zs) = splitAt (i-1) y in  ys ++ [newValue] ++ tail zs
        else y
    

    if index you give is wrong it returns original list.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-01 12:37

    Changing the nth element

    A common operation in many languages is to assign to an indexed position in an array. In python you might:

    >>> a = [1,2,3,4,5]
    >>> a[3] = 9
    >>> a
    [1, 2, 3, 9, 5]
    

    The lens package gives this functionality with the (.~) operator. Though unlike in python the original list is not mutated, rather a new list is returned.

    > let a = [1,2,3,4,5]
    > a & element 3 .~ 9
    [1,2,3,9,5]
    > a
    [1,2,3,4,5]
    

    element 3 .~ 9 is just a function and the (&) operator, part of the lens package, is just reverse function application. Here it is with more common function application.

    > (element 3 .~ 9) [1,2,3,4,5]
    [1,2,3,9,5]
    

    Assignment again works perfectly fine with arbitrary nesting of Traversables.

    > [[1,2,3],[4,5,6]] & element 0 . element 1 .~ 9
    [[1,9,3],[4,5,6]]
    

    or

    > set (element 3) 9 [1,2,3,4,5,6,7]
    

    Or if you want to effect multiple elements you can use:

    > over (elements (>3)) (const 99) [1,2,3,4,5,6,7]
    > [1,2,3,4,99,99,99]
    

    Working with types other then lists

    This is not just limited to lists however, it will work with any datatype that is an instance of the Traversable typeclass.

    Take for example the same technique works on trees form the standard containers package.

     > import Data.Tree
     > :{
     let
      tree = Node 1 [
           Node 2 [Node 4[], Node 5 []]
         , Node 3 [Node 6 [], Node 7 []]
         ]
     :}
    > putStrLn . drawTree . fmap show $ tree
    1
    |
    +- 2
    |  |
    |  +- 4
    |  |
    |  `- 5
    |
    `- 3
       |
       +- 6
       |
       `- 7
    > putStrLn . drawTree . fmap show $ tree & element 1 .~ 99
    1
    |
    +- 99
    |  |
    |  +- 4
    |  |
    |  `- 5
    |
    `- 3
       |
       +- 6
       |
       `- 7
    > putStrLn . drawTree . fmap show $ tree & element 3 .~ 99
    1
    |
    +- 2
    |  |
    |  +- 4
    |  |
    |  `- 99
    |
    `- 3
       |
       +- 6
       |
       `- 7
    > putStrLn . drawTree . fmap show $ over (elements (>3)) (const 99) tree
    1
    |
    +- 2
    |  |
    |  +- 4
    |  |
    |  `- 5
    |
    `- 99
       |
       +- 99
       |
       `- 99
    
    0 讨论(0)
  • 2020-12-01 12:39

    I'm not sure what you are trying to do. If you only need to generate ["Off","Off","On","Off"] you can do it explicitly. Generally speaking, one should avoid modifying state in haskell.

    Perhaps what you want is a function to "modify" (generate a new element with a different value) the nth element of a list? Don gives a very general approach to this kind of problem. You can also use explicit recursion:

     replaceNth :: Int -> a -> [a] -> [a]
     replaceNth _ _ [] = []
     replaceNth n newVal (x:xs)
       | n == 0 = newVal:xs
       | otherwise = x:replaceNth (n-1) newVal xs
    

    Haskell provides excellent features for list manipulation. If you dont know them already filter, map, and foldr/foldl are all worth looking at, as are list comprehensions.

    0 讨论(0)
提交回复
热议问题