Home > Software design >  What means of {*} in dict syntax in tcl
What means of {*} in dict syntax in tcl

Time:10-06

In tcl, there are some code idioms I am not familiar with, what {*} means in dict creat?

namespace eval ::resistorColor {
    variable colors [dict create {*}{
        black   0
        brown   1
        red     2
        orange  3
        yellow  4
        green   5
        blue    6
        violet  7
        grey    8
        white   9
    }]
}

CodePudding user response:

It's not an idiom, it's one of the basic rules of Tcl syntax: https://www.tcl.tk/man/tcl/TclCmd/Tcl.html#M9 .

It's being used here because the key/value pairs for the dict have been written as a list enclosed in {}, this allows them to be written on separate lines. But the dict create command doesn't want a single list, it wants the keys and values passed as separate arguments. So {*} is being used to split that list apart into the separate arguments for the dict command.

An alternative to this would be to use backslashes to continue the list of arguments for dict on multiple lines:

variable colors [dict create \
    black   0 \
    brown   1 \
    red     2 \
    ...etc...

CodePudding user response:

A well-formed list can also be used as a dictionary:

% set colors {
    black   0
    brown   1
    red     2
    orange  3
    yellow  4
    green   5
    blue    6
    violet  7
    grey    8
    white   9
}

% dict get $colors violet
7

I like to use the dict (and list) commands when constructing things to make the intent of the code quite obvious: "I will use this as a dict"

  • Related