Updated 2012-09-08 16:27:37 by LkpPo

What would it take to do classic iterators in Tcl? Do we need 'em? Dunno, but here is a contrived example in Itcl for the curious. -- Todd Coram
 package require Itcl

 itcl::class BiDirectionalIterator {
    variable pos -1
    variable end -1
    method first {} {
        set pos 0
        return $this
    }
    method next {{inc 1}} {
        set pos [expr {$pos + $inc}]
        if {$pos <= $end} {
            return $this
        }
        return {}
    }
    method prev {{decr 1}} {
        set pos [expr {$pos - $decr}]
        if {$pos >= 0} {
            return $this
        }
        return {}
    }
    method last {} {
        set pos $end
        return $this
    }

    method value {} abstract
 }

 itcl::class String {
    inherit BiDirectionalIterator
    variable string
    constructor {str} {
        set string $str
        set end [string length $str]
    }
    method value {} {
        return [string index $string $pos]
    }

 }

 itcl::class Tuple {
    inherit BiDirectionalIterator
    variable tuple
    constructor {tp} {
        set tuple $tp
        set end [llength $tuple]
    }
    method value {} {
        return [lindex $tuple $pos]
    }
 }

 proc reverse {obj} {
    set iter [$obj last]
    puts -nonewline "Reversed = <"
    while {$iter != {}} {
        puts -nonewline [$iter value]
        set iter [$iter prev]
    }
    puts ">"
 }

 proc every_other {obj} {
    set iter [$obj first]
    puts -nonewline "Every other = <"
    while {$iter != {}} {
        puts -nonewline [$iter value]
        set iter [$iter next 2]
    }
    puts ">"
 }

 String s "Hello World!"
 Tuple t {1 2 3 4 5 6}

 reverse s
 reverse t

 every_other s
 every_other t