From 5d028fe030050f6e593af760d9005b02d24a6b83 Mon Sep 17 00:00:00 2001 From: Joeri Exelmans Date: Mon, 16 Jun 2025 13:17:10 +0200 Subject: [PATCH] fix bug in dict comparison --- lib/compare/structures.js | 10 ++++++---- lib/structures/dict.js | 7 ++++--- tests/dict.js | 29 +++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 7 deletions(-) create mode 100644 tests/dict.js diff --git a/lib/compare/structures.js b/lib/compare/structures.js index 31e68ae..639ad4e 100644 --- a/lib/compare/structures.js +++ b/lib/compare/structures.js @@ -77,8 +77,10 @@ export const compareDicts = compareKeys => compareValues => x => y => { // because of the underlying red-black tree, iteration happens in ordered fashion const iterate = iterX => iterY => match(readDict(iterX)) - (entryX => + (_ => 0) // end of iteration (dicts are equal) + (entryX => // entry... match(readDict(iterY)) + (_ => {throw new Error("this can never happen");}) (entryY => compareKeys (getLeft(getLeft(entryX))) (getLeft(getLeft(entryY))) @@ -87,9 +89,9 @@ export const compareDicts = compareKeys => compareValues => x => y => { (getRight(getLeft(entryY))) || iterate (getRight(entryX)) - (getRight(entryY))) - (_ => 0)) - (_ => 0); // we made it, dicts are equal + (getRight(entryY)) + ) + ); return iterate(firstDict(x))(firstDict(y)); })(); }; diff --git a/lib/structures/dict.js b/lib/structures/dict.js index 2a3813d..53a7456 100644 --- a/lib/structures/dict.js +++ b/lib/structures/dict.js @@ -1,3 +1,4 @@ +import { unit } from "../primitives/unit.js"; import { RBTreeWrapper } from "../util/rbtree_wrapper.js"; import { indent } from "../util/util.js"; import { newProduct } from "./product.js"; @@ -32,13 +33,13 @@ export const last = dict => dict.tree.end; export const read = iter => { if (iter !== undefined && iter.valid) { return newRight( - newProduct( - newProduct(iter.key)(iter.value) + newProduct + (newProduct(iter.key)(iter.value)) (iter.clone().next()) - ) ); } else { + // end of iteration return newLeft(unit); } }; diff --git a/tests/dict.js b/tests/dict.js new file mode 100644 index 0000000..285e638 --- /dev/null +++ b/tests/dict.js @@ -0,0 +1,29 @@ +import assert from "node:assert"; + +import { compareInts, compareStrings } from "../lib/compare/primitives.js"; +import { compareDicts } from "../lib/compare/structures.js"; +import { emptyDict, set } from "../lib/structures/dict.js"; + +const cmpFn = compareDicts(compareStrings)(compareInts); + +const e = emptyDict(compareStrings); +const f = set(e)("x")(1n); +const g = set(f)("y")(2n); + +assert.equal( + cmpFn(e)(e), + 0, + "empty dict should be equal to itself" +); + +assert.equal( + cmpFn(g)(g), + 0, + "dict should always equal itself" +); + +assert.equal( + cmpFn(f)(g), + -1, + "f is smaller" +);