Menu: Difference between revisions
Content added Content deleted
(added ocaml) |
(→Tcl: Added implementation) |
||
Line 93: | Line 93: | ||
Which is from the three pigs: 3 |
Which is from the three pigs: 3 |
||
You chose: tick tock</pre> |
You chose: tick tock</pre> |
||
=={{header|Tcl}}== |
|||
<lang tcl>proc select {prompt choices} { |
|||
set nc [llength $choices] |
|||
if {!$nc} { |
|||
return "" |
|||
} |
|||
set numWidth [string length $nc] |
|||
while true { |
|||
for {set i 0} {$i<$nc} {} { |
|||
set s [lindex $choices $i] |
|||
incr i |
|||
puts [format " %-*d: %s" $numWidth $i $s] |
|||
} |
|||
puts -nonewline "$prompt: " |
|||
flush stdout |
|||
gets stdin num |
|||
if {[string is int -strict $num] && $num >= 1 && $num <= $nc} { |
|||
incr num -1 |
|||
return [lindex $choices $num] |
|||
} |
|||
} |
|||
}</lang> |
|||
Testing it out interactively... |
|||
<lang tcl>% select test {} |
|||
% puts >[select "Which is from the three pigs" { |
|||
"fee fie" "huff and puff" "mirror mirror" "tick tock" |
|||
}]< |
|||
1: fee fie |
|||
2: huff and puff |
|||
3: mirror mirror |
|||
4: tick tock |
|||
Which is from the three pigs: 0 |
|||
1: fee fie |
|||
2: huff and puff |
|||
3: mirror mirror |
|||
4: tick tock |
|||
Which is from the three pigs: skdfjhgz |
|||
1: fee fie |
|||
2: huff and puff |
|||
3: mirror mirror |
|||
4: tick tock |
|||
Which is from the three pigs: |
|||
1: fee fie |
|||
2: huff and puff |
|||
3: mirror mirror |
|||
4: tick tock |
|||
Which is from the three pigs: 5 |
|||
1: fee fie |
|||
2: huff and puff |
|||
3: mirror mirror |
|||
4: tick tock |
|||
Which is from the three pigs: 2 |
|||
>huff and puff<</lang> |