Skip to content

Commit

Permalink
Merge pull request #127 from skx/sort-hash-to-string
Browse files Browse the repository at this point in the history
When converting hashes to strings, sort their keys first.
  • Loading branch information
skx authored Feb 12, 2023
2 parents 0f8f01a + 685cce2 commit 51e0a83
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
2 changes: 2 additions & 0 deletions .github/run-tests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ echo "Launching shadowed-variable check .."
go vet -vettool=$(which shadow) ./...
echo "Completed shadowed-variable check .."

go env -w GOFLAGS="-buildvcs=false"

# Run golang tests
go test ./...

Expand Down
6 changes: 6 additions & 0 deletions eval/eval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,12 @@ a
{"(* 4 -1)", "-4"},
{"(# 3 2)", "9"},

// hash equality
{`(eq { :name "Ale" :age 3}
{ :age 3 :name "Ale"})`, "#t"},
{`(eq { :name "ale" :age 3}
{ :age 3 :name "Ale"})`, "#f"},

// since we're variadic we start with the first
// number, and apply the operation to any subsequent
// ones.
Expand Down
26 changes: 24 additions & 2 deletions primitive/hash.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package primitive

import "sort"

// Hash holds a collection of other types, indexed by string
type Hash struct {

Expand Down Expand Up @@ -51,12 +53,32 @@ func (h *Hash) SetStruct(name string) {
}

// ToString converts this object to a string.
//
// Note that we sort the keys before returning the stringified object,
// which allows us to use the "eq" test on hashes with identical key/values,
// regardless of their ordering.
func (h Hash) ToString() string {

// Output prefix.
out := "{\n"
for k, v := range h.Entries {
out += "\t" + k + " => " + v.ToString() + "\n"

// Get the keys in our hash.
keys := []string{}

for x := range h.Entries {
keys = append(keys, x)
}

// Sort the list of keys
sort.Strings(keys)

// Now we can get a consistent ordering for our
// hash keys/value pairs.
for _, key := range keys {
out += "\t" + key + " => " + h.Entries[key].ToString() + "\n"
}

// Terminate the string representation and return.
out += "}"
return out
}
Expand Down

0 comments on commit 51e0a83

Please sign in to comment.