Haskell replace element in list

后端 未结 4 1801
我在风中等你
我在风中等你 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: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

提交回复
热议问题