elvish icon indicating copy to clipboard operation
elvish copied to clipboard

Require map keys to be homogenous to avoid confusion between `num` and `string` type

Open krader1961 opened this issue 2 years ago • 3 comments

The discussion about possibly sorting the output of the keys command was side-tracked by my observation that map keys can be heterogeneous types. Which is why I'm opening this issue. Very few programming languages allow heterogeneous key types. And most don't allow heterogeneous value types but that's not what this issue is about.

The primary problem for a language like Elvish is that numbers are treated as strings unless in an explicit numeric context such as addition. The problem is that Elvish map keys are inherently type agnostic. Thus it is possible to accidentally create two keys that were intended to be identical but are not. For example:

elvish> var k1 = 1
elvish> var k2 = (num 1)
elvish> var m = [&$k1='string 1' &$k2='number 1']
elvish> pprint $m
[
 &(num 1)=	'number 1'
 &1=	'string 1'
]

The confusion between numbers as strings and numbers as the num type is only the most likely cause of problems. There are other, slightly less likely to occur, examples such as using a list as a map key when an element of the list was intended as the key.

My original idea was to make inserting a map key whose type is different from an existing map key a run-time exception worthy event. Primarily to avoid complicating the syntax to include some form of declaration of the key type. I'm not convinced that is the best long term course of action. However, I believe it is preferable to the current situation that can silently elide mistakes involving numbers as strings and the Elvish num type.

krader1961 avatar Jul 07 '22 03:07 krader1961

Very few programming languages allow heterogeneous key types

I think at least Java, Python, Ruby, Lua, Lisp do

lispnik avatar Jul 11 '22 18:07 lispnik

@lispnik, I can only speak to Python from my personal experience. That includes resolving a bug due to inserting a map key that should have been a number rather than a string. Allowing heterogeneous key types is more likely, in my experience, to result in unexpected behavior than value. I invite you to provide some concrete examples where heterogenous map keys are useful and justify such flexibility.

krader1961 avatar Jul 14 '22 03:07 krader1961

See also issue #1025 about sorting the output of the keys command and the fact that order doesn't support ordering heterogenous value types.

krader1961 avatar Aug 11 '22 01:08 krader1961