Skip to content

Instantly share code, notes, and snippets.

@sebres
Created October 23, 2019 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebres/9a812871fdcc46a0eba8e6368b8176cd to your computer and use it in GitHub Desktop.
Save sebres/9a812871fdcc46a0eba8e6368b8176cd to your computer and use it in GitHub Desktop.
(experimental) range -- create a list generating a sequence of numbers or strings
if {[namespace which -command ::tcl::mathfunc::strincr] eq ""} {
proc ::tcl::mathfunc::strincr {v {increment}} {
string trimleft [binary format I* [expr {"0b[binary scan $v B* v; set v]" + $increment}]] \x00
}
}
proc range args {
set op "<"; set step 1
switch -exact -- [llength $args] \
1 { lassign $args to; set from [expr {$to*0}] } \
2 { lassign $args from to;
if {$from in {< <= > >=}} { set op $from; set from [expr {$to*0}] } \
elseif {$from >= $to} { set op ">"; set step -1 }
} \
3 { lassign $args from to step;
if {$from in {< <= > >=}} { set op $from; set from [expr {$to*0}] } \
elseif {$to in {< <= > >=}} { set op $to; set to $step; set step 1 } \
elseif {$from >= $to && $step < 0} { set op ">" }
} \
4 { lassign $args from op to step } \
default { return -code error "wrong # args: should be \"range ?from? ?op? to ?step?\"" }
set op "::tcl::mathop::$op"
if {[string is wideinteger -strict $to] || [regexp {^[+\-]?\d+(?:\.\d*)?} $to]} {
set res [list $from]
while {[$op [set from [expr {$from + $step}]] $to]} { lappend res $from }
} else {
set res [list $from]
while {[$op [set from [expr {strincr($from, $step)}]] $to]} { lappend res $from }
}
return $res
}
if 0 {;#
% range 4
0 1 2 3
% range <= 4
0 1 2 3 4
% range 5 0
5 4 3 2 1
% range 10 >= 4 -2
10 8 6 4
% range <= 4.0 2
0.0 2.0 4.0
% range 0.0 10 1.5
0.0 1.5 3.0 4.5 6.0 7.5 9.0
% range C @
C B A
% range A <= Z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
% range aaa aza 256
aaa aba aca ada aea afa aga aha aia aja aka ala ama ana aoa apa aqa ara asa ata aua ava awa axa aya
};#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment