Re: Array get element with default (no error if not exist)

Liste des GroupesRevenir à cl tcl 
Sujet : Re: Array get element with default (no error if not exist)
De : ralfixx (at) *nospam* gmx.de (Ralf Fassel)
Groupes : comp.lang.tcl
Date : 16. Aug 2024, 10:11:29
Autres entêtes
Message-ID : <ygao75szvb2.fsf@akutech.de>
References : 1
User-Agent : Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux)
* RodionGork <rodiongork@github.com>
| Is there some motivation why some command for get-with-default is not
| implemented, e.g.
>
| puts [array peek $a 2 "default value"]

Most probably because up to now nobody required it so badly that s/he
implemented it, since the [info exists] approach is not too bad IMHO.

    proc array_peek {arr key default} {
      upvar $arr a
      if {![array exists a] || ![info exists a($key)]} {
        return $default
      }
      return $a($key)
    }
    array set a {1 one}
    array_peek a 1 "default value"
    => one
    array_peek a 2 "default value"
    => default value

Or you could set up a read-trace on the array to provide non-existing values:

     array set a {}
     trace add variable a read set_array_default
     proc set_array_default {name1 name2 op} {
        upvar a $name1
        # puts stderr "set_array {$name1} {$name2} {$op}"
        if {![info exists a($name2)]} {
          set a($name2) "default"
        }
     }
     set a(2)
     => default

Though that would alter the array and make the key exists which might
not be what you want.

HTH
R'

Date Sujet#  Auteur
16 Aug 24 * Array get element with default (no error if not exist)8RodionGork
16 Aug 24 +* Re: Array get element with default (no error if not exist)5Ralf Fassel
17 Aug 24 i`* Re: Array get element with default (no error if not exist)4RodionGork
17 Aug 24 i `* Re: Array get element with default (no error if not exist)3Rich
18 Aug 24 i  `* Re: Array get element with default (no error if not exist)2RodionGork
18 Aug 24 i   `- Re: Array get element with default (no error if not exist)1Rich
16 Aug 24 `* Re: Array get element with default (no error if not exist)2Emiliano
16 Aug 24  `- Re: Array get element with default (no error if not exist)1Ralf Fassel

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal