Replace individual list elements in Haskell?

Typically, you modify elements of a list by splitting the list, replacing an element, and joining it back together.

To split a list at an index, we have:

 splitAt :: Int -> [a] -> ([a], [a]) 

which you can use to break up a list, like so:

 > splitAt 2 ["Off","Off","Off","Off"] 
 (["Off","Off"],["Off","Off"])

now you just need to pop the head element of the snd component of the list. This is easily done with pattern matching:

 > let (x,_:ys) = splitAt 2 ["Off","Off","Off","Off"]
 > x
 ["Off","Off"]
 > ys
 ["Off"]

you can now join the list back together, with an “On”:

 > x ++ "On" : ys
 ["Off","Off","On","Off"]

I’ll leave it to you to put those pieces together into a single function.


As a style note, I’d suggest using a new custom data type, instead of String for your toggles:

 data Toggle = On | Off deriving Show

Leave a Comment