Pages

Symbol Literal - I'm probably abusing it

Friday, October 25, 2013

Yesterday suddenly I felt I wanted to implement ancient famous programming stuff, Game of Life http://en.wikipedia.org/wiki/Conway's_Game_of_Life.
I had sought something suitable for polymer.dart experience with having fun. Firstly I decided not to use polymer then later on tried to use it in order to compare them. I've enjoyed the implementing (except that I got confused from mysterious error output repeatedly on console about build.dart, still not resolved but works).

https://github.com/ntaoo/game_of_life.dart/tree/non-polymer
You can clone it, then run on Dartium.

Through writing the code, as you can see in index.dart, I use symbol literals like #live, #dead.
Symbol literal is just short version of const Symbol(‘id’) which you may have seen in mirror based codes. Recently the symbol literal have been added to Dartlang, so I felt I wanted to use the new expression instead of String.
https://github.com/ntaoo/game_of_life.dart/blob/non-polymer/web/index.dart
It workd as I expected. But when I felt I wanted to use switch statements instead of if-else statements, I stumbled on a error.

From the if-else



    if (_currentState == #dying) {
      _currentState = #dead;
    } else if (_currentState == #aboring) {
      _currentState = #live;
    } else {
      // do nothing
    }


To the switch statements



    switch (_currentState) {
      case #dying:
        _currentState = #dead;
        break;
      case #aboring:
        _currentState = #live;
        break;
    }

     -> // Error: type class of case expression must not implement operator == case 

I confirmed the error was reproduced in a simple example as below.



  pass() {
    var a = 'a';
    var b = 'b';
  
    switch (a) {
      case 'a':
        print('a');
        break;
      case 'b':
        print('b');
        break;
    }
    // -> 'a'
  }
  
  error() {
    var a = #a;
    var b = #b;
  
    switch (a) {
      case #a:
        print('a');
        break;
      case #b:
        print('b');
        break;
    }
    // Error: type class of case expression must not implement operator == case #a:
  }
  
  main() {
    pass();
    error();
  }


I was curious about it, so I referred dart language specification.
https://www.dartlang.org/docs/spec/latest/dart-language-specification.html#h.qke6yiz8c62q
It explains concisely about the use case of symbol -- reflection and minification, also explains the handy syntax becomes addictive. Yes, I did. Should I use String instead of Symbol literal in the case? Probably yes, I think.

No comments:

Post a Comment