Skip to content

associative arrays ("dictionaries") would be useful #390

@maxfl

Description

@maxfl

I thought I will implement it by myself, but currently I have no time for it. So I just write down the idea in case somebody will like it and implement, or in case I will return back to it next year.

The idea is to extend the definition of variables so the strings could be used as the access-keys in addition to integer numbers. One can think of them as std::map<string,string>, or python dictionary, or lua tables which are the closest. Possibility to use dictionaries exists also in bash/zsh, though dictionaries are distinct from ordinary variables.

Why it is useful?

The latest example I saw is in __terlar_git_prompt, where you need to get a color and symbol for named elements in a list:

for i in $fish_prompt_git_status_order
    if contains $i in $gs
      echo 'set_color $fish_color_git_'$i
      echo 'echo -n $fish_prompt_git_status_'$i
    end
end | .

Where $i runs the items from the list: added modified deleted etc.

If one could use variables as dictionaries, this piece of code could be rewritten in the following way:

for i in $fish_prompt_git_status_order
    if contains $i in $gs
      set_color $fish_color_git[$i]
      echo -n $fish_prompt_git_status[$i]
    end
end

Which for me looks much nicer and simpler.

How not to break the ordinary variables?

That is actually very simple. The idea is almost the same as in lua tables (http://lua-users.org/wiki/TablesTutorial):

  • If the key is number, it refers to the 'array' part of the variable, which is what a variables currently.
  • If the key is a string (starts from a letter for example), it refers to the dictionary part.
  • Dictionary part should not affect all the previous behaviour. "$variable" is expanded to a list of array part. 'count $variable' will print the number of elements in the array part.
  • "set var " also works only with the array part.

The differences comes with handling subscription:

  • 'set var[key] value' or 'set var[key1 key2] value1 value2' should be expanded to handle string keys.
  • $var[key] or $var[$key] or $var[key1 key2] should return values, which were previously set.
  • There should also be functions for working with dictionaries, like getting list of keys for iteration, or getting the number of elements in dictionary part.
set var[a b c] d e f
echo $var  #-><nothing>
count $var #->0
get --size var   #-> 3
get --keys var   #-> a b c 
get --values var #-> d e f
get --pairs var  #-> a d b e c f

Other issues

  • One should also update universal variables handling.
  • Dictionary part of the variables could not be exported.

Thats it

Any ideas/thoughts/critics are appreciated.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions