home *** CD-ROM | disk | FTP | other *** search
/ H4CK3R 5 / hacker05 / 05_HACK_05.ISO / programacao / freewrap / TCLLIBsampleApp.exe / sample / tcllib / tcllib1.0 / textutil / textutil.tcl < prev    next >
Encoding:
Text File  |  2001-08-17  |  1.7 KB  |  65 lines

  1. package require Tcl 8.2
  2. namespace eval textutil {
  3.     namespace export strRepeat
  4.     
  5.     variable HaveStrRepeat [ expr {![ catch { string repeat a 1 } ]} ]
  6.  
  7.     if {0} {
  8.     # Problems with the deactivated code:
  9.     # - Linear in 'num'.
  10.     # - Tests for 'string repeat' in every call!
  11.     #   (Ok, just the variable, still a test every call)
  12.     # - Fails for 'num == 0' because of undefined 'str'.
  13.  
  14.     proc StrRepeat { char num } {
  15.         variable HaveStrRepeat
  16.         if { $HaveStrRepeat == 0 } then {
  17.         for { set i 0 } { $i < $num } { incr i } {
  18.             append str $char
  19.         }
  20.         } else {
  21.         set str [ string repeat $char $num ]
  22.         }
  23.         return $str
  24.     }
  25.     }
  26.  
  27. }
  28.  
  29. if {$::textutil::HaveStrRepeat} {
  30.     proc ::textutil::strRepeat {char num} {
  31.     return [string repeat $char $num]
  32.     }
  33. } else {
  34.     proc ::textutil::strRepeat {char num} {
  35.     if {$num <= 0} {
  36.         # No replication required
  37.         return ""
  38.     } elseif {$num == 1} {
  39.         # Quick exit for recursion
  40.         return $char
  41.     } elseif {$num == 2} {
  42.         # Another quick exit for recursion
  43.         return $char$char
  44.     } elseif {0 == ($num % 2)} {
  45.         # Halving the problem results in O (log n) complexity.
  46.         set result [strRepeat $char [expr {$num / 2}]]
  47.         return "$result$result"
  48.     } else {
  49.         # Uneven length, reduce problem by one
  50.         return "$char[strRepeat $char [incr num -1]]"
  51.     }
  52.     }
  53. }
  54.  
  55.  
  56.  
  57. source [ file join [ file dirname [ info script ] ] adjust.tcl ]
  58. source [ file join [ file dirname [ info script ] ] split.tcl ]
  59. source [ file join [ file dirname [ info script ] ] tabify.tcl ]
  60. source [ file join [ file dirname [ info script ] ] trim.tcl ]
  61.  
  62. # Do the [package provide] last, in case there is an error in the code above.
  63. package provide textutil 0.2
  64.  
  65.