- Write a procedure to reverse a string. If you wrote an iterative solution, now write a recursive solution or vice versa.
#!/usr/bin/tclsh
# iterative solution:
proc rev_str_iter { input } { for {set idx [string length \(input]} {\)idx > 0} {incr idx -1} { append res [string index $input [expr $idx-1]] } return $res } # recursive solution: proc rev_str_recur { input } { set len [string length $input] if {[expr $len - 1] > 0} { append res [rev_str_recur [string range $input 1 end]] \ [string index $input 0] } else { set res $input } return $res } set m "abcdefg" set n [rev_str_iter $m] puts $n set n2 [rev_str_recur $m] puts $n2
- Repeat the previous exercise but with a list instead of a string.
#!/usr/bin/tclsh # iterative solution: proc rev_list_iter { input } { for {set idx [llength \(input]} {\)idx > 0} {incr idx -1} { lappend res [lindex $input [expr $idx-1]] } return $res } # recursive solution: proc rev_list_recur { input } { set len [llength $input] if {[expr $len - 1] > 0} { set res [concat [rev_list_recur [lrange $input 1 end]] [lindex $input 0]] } else { set res $input } return $res } set m "a b c d e g" set n [rev_list_iter $m] puts $n set n2 [rev_list_recur $m] puts $n2
- Write a procedure to rename all the files in a directory ending with .c to names ending in ".cc“.
#!/usr/bin/tclsh foreach file_name [glob *.c] { file rename $file_name [append file_name c] }
- Write a procedure that takes a list of variable names and a list of values, and sets each variable in the list to the respective value in the other list. Think of different alternatives to handle the case when the lists are of different lengths.
#!/usr/bin/tclsh proc assign {names values} { if {[llength \(names] > [llength $values]} { set len [llength $values] } else { set len [llength $names] } for {set idx 0} {\)idx<$len} {incr idx} { set var_name [lindex $names $idx] set $var_name [lindex $values $idx] puts [concat $var_name = [set $var_name]] } } set names "za bb ee dk" set values "11 32 53 94 5" assign $names $values