Replace individual list elements in Haskell?

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

    Here is a one liner that works perfectly

    replace pos newVal list = take pos list ++ newVal : drop (pos+1) list
    

    I doesn't seem efficient to do this kind of things in haskell.

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

    I think you should consider using a data structure other than List. For example, if you just want to have a state of four on/off switches then:

    data State = St { sw1, sw2, sw3, sw4 :: Bool }
    

    For a dynamic number of switches then consider a mapping from switch name to Bool.

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

    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
    
    0 讨论(0)
提交回复
热议问题