Lisp and Erlang Atoms, Ruby and Scheme Symbols. How useful are they?

前端 未结 13 1592
一个人的身影
一个人的身影 2020-12-12 18:08

How useful is the feature of having an atom data type in a programming language?

A few programming languages have the concept of atom or symbol to represent a consta

13条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-12 18:48

    In some languages, associative array literals have keys that behave like symbols.

    In Python[1], a dictionary.

    d = dict(foo=1, bar=2)
    

    In Perl[2], a hash.

    my %h = (foo => 1, bar => 2);
    

    In JavaScript[3], an object.

    var o = {foo: 1, bar: 2};
    

    In these cases, foo and bar are like symbols, i.e., unquoted immutable strings.

    [1] Proof:

    x = dict(a=1)
    y = dict(a=2)
    
    (k1,) = x.keys()
    (k2,) = y.keys()
    
    assert id(k1) == id(k2)
    

    [2] This is not quite true:

    my %x = (a=>1);
    my %y = (a=>2);
    
    my ($k1) = keys %x;
    my ($k2) = keys %y;
    
    die unless \$k1 == \$k2; # dies
    

    [1] In JSON, this syntax is not allowed because keys must be quoted. I don't know how to prove they are symbols because I don't know how to read the memory of a variable.

提交回复
热议问题