Looping over dictionary while using different values to insert and remove keys

125 views Asked by At

I'm using vertices and a Data.Map.Strict, where I need to implement a capture move for the game Checkers. cMove is supposed to take a vertex k and a list of vertices ks and a map myMap. cMove needs to check if the new vertex (the position which k will get when it jumps over a vertex in ks) is in myMap, as myMap contains the positions of all the pieces on the board. k and k1 (a vertex in ks) should be removed from myMap and the new vertex should be inserted into myMap, where the new vertex should be used to check the next vertex in ks and so on, till there are no more elements in the list. I have tried this:

type Key = (Integer, Integer)

cMove :: Key -> [Key] -> Map Key Bool -> Map Key Bool
cMove k ks myMap = foldr cMoves' myMap ks
    where
        cMoves' :: Key -> Map Key Bool -> Map Key Bool
        cMoves' k1 myMap = case M.lookup k' myMap of
            Nothing -> M.insert k' False (M.delete k myMap)
            Just x -> myMap
          where
            k' = (2 * fst k1 - fst k, 2 * snd k1 - snd k)

which iterates through the list k1 as supposed and inserts the new vertex. The problem here is, that k1 is not getting removed and the new vertex is not used instead of k. How do I achieve this?

If any part of my question seems vague, don't hesitate to let me know.

1

There are 1 answers

3
Cactus On BEST ANSWER

If I understand the question right, you want to change k to k' from iteration to iteration. You can do that by changing the state of your fold to include k as well:

cMove :: Key -> [Key] -> Map Key Bool -> Map Key Bool
cMove k ks myMap = snd $ foldr cMoves' (k, myMap) ks
    where
        cMoves' :: Key -> (Key, Map Key Bool) -> (Key, Map Key Bool)
        cMoves' k1 (k, myMap) = case M.lookup k' myMap of
            Nothing -> (k1, M.insert k' False . M.delete k . M.delete k1 $ myMap)
            Just x -> (k, myMap)
          where
            k' = (2 * fst k1 - fst k, 2 * snd k1 - snd k)