0
votes

So I'm attempting to create a Hash Map where each key is an item on a board.

{[0 0] -1, [0 1] -1, [0 2] -1, [0 3] -1, [0 4] -1, [0 5] -1, [0 6] -1, [0 7] -1, [0 8] -1, [0 9] -1, [1 0] -1, [1 1] -1, [1 2] -1, [1 3] -1, [1 4] -1, [1 5] -1, [1 6] -1, [1 7] -1, [1 8] -1, [1 9] -1, [2 0] -1, [2 1] -1, [2 2] -1, [2 3] -1, [2 4] -1, [2 5] -1, [2 6] -1, [2 7] -1, [2 8] -1, [2 9] -1, [3 0] -1, [3 1] -1, [3 2] -1, [3 3] -1, [3 4] -1, [3 5] -1, [3 6] -1, [3 7] -1, [3 8] -1, [3 9] -1, [4 0] -1, [4 1] -1, [4 2] -1, [4 3] -1, [4 4] -1, [4 5] -1, [4 6] -1, [4 7] -1, [4 8] -1, [4 9] -1, [5 0] -1, [5 1] -1, [5 2] -1, [5 3] -1, [5 4] -1, [5 5] -1, [5 6] -1, [5 7] -1, [5 8] -1, [5 9] -1, [6 0] -1, [6 1] -1, [6 2] -1, [6 3] -1, [6 4] -1, [6 5] -1, [6 6] -1, [6 7] -1, [6 8] -1, [6 9] -1, [7 0] -1, [7 1] -1, [7 2] -1, [7 3] -1, [7 4] -1, [7 5] -1, [7 6] -1, [7 7] -1, [7 8] -1, [7 9] -1, [8 0] -1, [8 1] -1, [8 2] -1, [8 3] -1, [8 4] -1, [8 5] -1, [8 6] -1, [8 7] -1, [8 8] -1, [8 9] -1, [9 0] -1, [9 1] -1, [9 2] -1, [9 3] -1, [9 4] -1, [9 5] -1, [9 6] -1, [9 7] -1, [9 8] -1, [9 9] -1}

So far I have

(zipmap (for [x (range 10) y (range 10)] [x y]) (repeat -1))

And if I wanted the keys sorted:

(into (sorted-map) (zipmap (for [x (range 10) y (range 10)] [x y]) (repeat -1)))

In Python I can come up with the following dictionary comprehension:

board = {(x, y): -1 for x in range(5) for y in range(5)}

I'm wondering if I can do a similar thing in Clojure that's more readable / efficient than my current approach

1

1 Answers

1
votes

If you want to put together the key and the value inside the list comprehension, you can do this:

(into {} (for [x (range 10) y (range 10)] [[x y] -1]))

If you want a sorted map, you can simply replace the {} with a (sorted-map):

(into (sorted-map) (for [x (range 10) y (range 10)] [[x y] -1]))