Replace individual list elements in Haskell?

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

提交回复
热议问题