You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ClojureScript中zipmap生成有序映射异常问题求助

Hey there! Let's break down why you're seeing random order in your map and how to fix it.

Why zipmap is giving you unordered results

When you use zipmap, it returns a standard hash map (the {} syntax in ClojureScript). Hash maps are optimized for fast lookups, but they don’t preserve the order of insertion. The order you see when printing or iterating over them is determined by the hash values of the keys—with vector keys like [0 0] or [0 1], this hash-based order will look totally random. That’s why your map is coming out jumbled instead of following the sequence you expected from the combinatorics library.

How to get an ordered map

To keep your key-value pairs in the exact order you generate them, you need an ordered map. In ClojureScript, cljs.core/ordered-map is built for this purpose—it maintains insertion order no matter how many entries you have. Instead of using zipmap directly, you’ll create a sequence of [key value] pairs first, then "pour" that sequence into an ordered map using into.

Here’s how to adjust your code:
First, make sure you reference ordered-map (it’s part of core, no extra dependencies needed):

(require '[clojure.math.combinatorics :as combi]
         '[cljs.core :refer [ordered-map]])

Then generate your coordinate sequence, pair each coordinate with its index, and feed that into the ordered map:

;; Generate your grid coordinates (example: 10x10 grid)
(def coordinates (combi/cartesian-product (range 10) (range 10)))

;; Create [key value] pairs and convert to an ordered map
(def ordered-grid-map (into (ordered-map) (map vector coordinates (range))))

This ordered-grid-map will retain the exact order of your generated coordinates, so you’ll get {[0 0] 0, [0 1] 1, [0 2] 2, ...} just like you wanted.

A quick side note: You might have encountered array-map, which also preserves order for small datasets. But array-map automatically converts to a hash map once it has enough entries (usually 8+), so it’s not reliable for larger grids. ordered-map is the consistent choice here.

内容的提问来源于stack exchange,提问作者Benogi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:09:11