Implement syntax sugar for maps

73 views
Skip to first unread message

Syndrome Dayna

unread,
Aug 2, 2016, 3:55:03 AM8/2/16
to ceylon-users
shared void asd()
{    
    value map
= HashMap<String,Integer> {"A" -> 1};
 
   
// Increment stored integer
    map
.put("A", (map.get("A") else 0)+1); // <- Compiles, but not readable
    map
["A"] += 1; // <- Readable, but doesnt compile          
}


Lucas Werkmeister

unread,
Aug 2, 2016, 4:07:05 AM8/2/16
to ceylon...@googlegroups.com

https://github.com/ceylon/ceylon/issues/4148


--
You received this message because you are subscribed to the Google Groups "ceylon-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ceylon-users...@googlegroups.com.
To post to this group, send email to ceylon...@googlegroups.com.
Visit this group at https://groups.google.com/group/ceylon-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/ceylon-users/1e7212c4-616f-4494-ba75-ac861494ecb5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Syndrome Dayna

unread,
Aug 2, 2016, 5:51:31 AM8/2/16
to ceylon-users
This code does not satisfy the logic of language, because i didnt check for null.

map["A"] += 1; // <- Readable, but doesnt compile

Then I suggest another option:
// Increment stored integer
map
.put("A", (map.get("A") else 0)+1); // <- not readable
map
["A"] = (map["A"] else 0)+1; // <- readable


Nikolay Tsankov

unread,
Aug 5, 2016, 12:04:09 PM8/5/16
to ceylon-users
What I miss is the compute() and merge() methods, but one can always do something like:

import ceylon.collection {
    HashMap    
}
class MyMap<Key, Item>() extends HashMap<Key, Item>() given Key satisfies Object {
    
    shared void compute(Key key, Item(Item?) fun) {
        put(key, fun(get(key)));
    }
    
    shared void merge(Key key, Item item, Item(Item) fun) {
        put(key, fun(get(key) else item));
    }
}

shared void run() {
   value map = MyMap<String, Integer>();
   map.compute("A", (x) => x else 0 + 1);
   map.merge("A", 0 , Integer.plus(1));
}
Reply all
Reply to author
Forward
0 new messages