goby-lang / goby

Goby - Yet another programming language written in Go
MIT License
3.49k stars 171 forks source link

Sort Goby Hash Keys in Certain Order #265

Closed Alexius-Huang closed 7 years ago

Alexius-Huang commented 7 years ago

The hash pair order in REPL seems not corresponding to the input order, e.g., when I try to print out simple hash:

$ go run goby.go -i
Goby 0.0.9
» h = {a: "Hello", b: "World", c: "Goby"}
#=> <Instance of: Object>
» h
#=> { c: Goby, b: World, a: Hello }
» h
#=> { c: Goby, b: World, a: Hello }
» h
#=> { a: Hello, c: Goby, b: World }
» h
#=> { b: World, a: Hello, c: Goby }
» h
#=> { b: World, a: Hello, c: Goby }
» h
#=> { b: World, a: Hello, c: Goby }
» h
#=> { c: Goby, b: World, a: Hello }
» h
#=> { c: Goby, b: World, a: Hello }
»  

Any idea?

st0012 commented 7 years ago

@Maxwell-Alexius This is because we use Go's map to store pairs, and in Go map's key/value are random ordered.

Alexius-Huang commented 7 years ago

I'll try to find a solution for this case, thanks!

Alexius-Huang commented 7 years ago

@st0012 Maybe we can sort the keys in alphabetical order so that we can guarantee that the hash will be appear in certain order in Goby lang?

https://stackoverflow.com/questions/23330781/sort-golang-map-values-by-keys

Sort keys in alphabetical order: https://stackoverflow.com/questions/2038508/easy-way-to-get-the-keys-in-a-map-in-alphabetical-order

st0012 commented 7 years ago

@Maxwell-Alexius I think we should just sort them in toString method, and keep it random in other places. I remember I read a post about why Go made this random decision but I can't find it now. @hachi8833 Do you know why?

hachi8833 commented 7 years ago

Looks like the article is the one.

Alexius-Huang commented 7 years ago

@st0012 @hachi8833 Thanks, I think I can adjust this feature request which is listed below:

Proposal I. There is no need to sort or order the Hash key-value pairs. However, for some method implementation, like Hash#sorted_keys, we can return an array of keys of hash in alphabetical order. (Affect some Hash API method implementation in #247)

~Proposal II. Remain current arbitrary state of the key-value pairs in hash API, so if implementing Hash#keys, the keys may also in an arbitrary order. (Issue closed here, if anyone wants to change the Hash pairs order, they can reopen this issue)~

st0012 commented 7 years ago

I actually agree that the hash shouldn't guarantee the key's order, so I suggest keep it this way. But maybe we can provide some extra API like sorted_keys for those who need the keys sorted.

Alexius-Huang commented 7 years ago

Okay, got it ~

Alexius-Huang commented 7 years ago

This should be closed because PR #247 completed.