Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion pkg/lang/persistentarraymap.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ var (
_ IReduceInit = (*MapSeq)(nil)
_ IDrop = (*MapSeq)(nil)

_ ASeq = (*MapKeySeq)(nil)
_ ASeq = (*MapKeySeq)(nil)
_ IReduce = (*MapKeySeq)(nil)
_ IReduceInit = (*MapKeySeq)(nil)

_ ASeq = (*MapValSeq)(nil)
_ IReduce = (*MapValSeq)(nil)
Expand Down Expand Up @@ -563,6 +565,39 @@ func (s *MapKeySeq) HashEq() uint32 {
return aseqHashEq(&s.hasheq, s)
}

func (s *MapKeySeq) Reduce(f IFn) any {
count := 0
var res any
first := true
for seq := Seq(s); seq != nil; seq = seq.Next() {
count++
if first {
res = seq.First()
first = false
continue
}
res = f.Invoke(res, seq.First())
if IsReduced(res) {
return res.(IDeref).Deref()
}
}
if count == 0 {
return f.Invoke()
}
return res
}

func (s *MapKeySeq) ReduceInit(f IFn, init any) any {
res := init
for seq := Seq(s); seq != nil; seq = seq.Next() {
res = f.Invoke(res, seq.First())
if IsReduced(res) {
return res.(IDeref).Deref()
}
}
return res
}

////////////////////////////////////////////////////////////////////////////////

func NewMapValSeq(s ISeq) ISeq {
Expand Down
20 changes: 20 additions & 0 deletions test/glojure/test_glojure/basic.glj
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,24 @@
(is (:foo (meta ^:foo #{})))
(is (:foo (meta ^:foo {}))))

(deftest map-key-seq-reduce
(test-that "MapKeySeq implements reduce operations correctly"
(let [test-map {:a 1 :b 2 :c 3 :d 4 :e 5}]
;; Test mapv on keys (this was the original failing case)
(is (= 5 (count (mapv identity (keys test-map)))))
(is (vector? (mapv identity (keys test-map))))

;; Test reduce on keys
(is (= 5 (reduce (fn [acc _] (inc acc)) 0 (keys test-map))))

;; Test mapv with transformation on keys
(is (= 5 (count (mapv str (keys test-map)))))

;; Test that vals still work correctly
(is (= 5 (count (mapv identity (vals test-map)))))
(is (= 15 (reduce + (vals test-map))))

;; Test with namespace map keys (the original bug report case)
(is (number? (count (mapv str (keys (ns-map *ns*)))))))))

(run-tests)