Haskell replace element in list

后端 未结 4 1789
我在风中等你
我在风中等你 2020-12-31 01:31

Is there any built-in function to replace an element at a given index in haskell?

Example:

replaceAtIndex(2,\"foo\",[\"bar\",\"bar\",\"bar\"])

相关标签:
4条回答
  • 2020-12-31 02:09

    As far as I know (and can find) it does not exist by default. However, there exists splitAt in Data.List so:

    replaceAtIndex n item ls = a ++ (item:b) where (a, (_:b)) = splitAt n ls
    

    This is O(N) though. If you find yourself doing this a lot, look at another datatype such as array.

    0 讨论(0)
  • 2020-12-31 02:20

    If you need to update elements at a specific index, lists aren't the most efficient data structure for that. You might want to consider using Seq from Data.Sequence instead, in which case the function you're looking for is update :: Int -> a -> Seq a -> Seq a.

    > import Data.Sequence
    > update 2 "foo" $ fromList ["bar", "bar", "bar"]
    fromList ["bar","bar","foo"]
    
    0 讨论(0)
  • 2020-12-31 02:23

    There is actual arrays, but lists are really singly linked lists and the notion of replacing an element is not quite as obvious (and accessing an element at a given index may indicate that you shouldn't be using a list, so operations that might encourage it are avoided).

    0 讨论(0)
  • 2020-12-31 02:25

    Try this solution:

    import Data.List
    
    replaceAtIndex :: Int -> a -> [a] -> [a]    
    replaceAtIndex i x xs = take i xs ++ [x] ++ drop (i+1) xs
    

    It works as follows:

    get the first i items, add the value 'x', add the rest of i+1 items

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