Planet JFX

Tuples and Maps

118pages on
this wiki
Add New Page
Talk0 Share

This is a proposal that builds on Tuples_and_Arrays, and works well with Patterns.

A map is a finite function from a key to a value, with an enumerable domain. Map is a base class for array:

 class Map<KeyType, ValueType> ...
 class Array<ValueType> extends Map<Integer, ValueType>

A map contains a number of "pairs" [better name needed], each of which is an elemental (key,value) "map entry"..

Syntax of pairs is TBD, but we'll assume to following:


We could also have:

 name: value // Optional syntactic sugar for "name"->value

This integrates with keyword parameters, object literals, etc.

Idea: If we use the 'name: value' syntax for a pair with a literal string key, we could use the same braces as in enclosed expressions in string literals, since in both cases it's an "anti-quotation" operator:



 name: value

could be syntactic sugar for

 {"name"}: value

To construct a map use the same brackets as to construct an array:

 [ key1->value1, key2->value2, ...]

Indexing is done using the same function-call notation as for arrays:

 [ key1->value1, key2->value2, ...](key2) --> value2

If there is no value for a given key, the lookup returns a special distinguished value. I'll assume this the empty tuple (). This assumes that values in maps are always single items. It also assumes that == against () works as expected, to make it easy to check:

 let value = map(index);
 if value == () then "missing" else use(value)

Back to square brackets: The result is an array if no items are pairs If any item is a pair, the result is a map. In case of a mix of a pairs and non-pairs, the non-pair is converted to a pair by giving it the lowest non-negative integer key not encountered in previous items.

If two pairs in a map constructor have the same keys, the latter one wins:

 ["a"->1, "b"->2, "a"->3]("a") ==> 3

Using pairs is useful for arrays too. A problem is typing: using a pair yields a map rather than an array. A solution is a useful array constructor function, perhaps:

 makeArray(length, defaultValue, valuesPair...)
 makeArray(5, -1, 4->40, 2->20) ==> [-1, -1, 20, -1, 40]

An alternative is an APL=like "take" operator, which coerces a map to an array of a given length.

The pair operator can be used in patterns, such as in a for-expressions:

 [for (k->v in map) k->(2*v)]

This doubles all the values in map. An alternative is a pseudo-variable, like the current indexof operator. However, we might rename it to "key":

 [for (v in map) (key v)->(2*v)]

Back to OpenJFX Compiler.

Ad blocker interference detected!



Also on Fandom

Random Wiki