This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

11
Task/Menu/0DESCRIPTION Normal file
View file

@ -0,0 +1,11 @@
Given a list containing a number of strings of which one is to be selected and a prompt string, create a function that:
* Print a textual menu formatted as an index value followed by its corresponding string for each item in the list.
* Prompt the user to enter a number.
* Return the string corresponding to the index number.
The function should reject input that is not an integer or is an out of range integer index by recreating the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the four phrases: “<tt>fee fie</tt>”, “<tt>huff and puff</tt>”, “<tt>mirror mirror</tt>” and “<tt>tick tock</tt>” in a list.
Note: This task is fashioned after the action of the [http://www.softpanorama.org/Scripting/Shellorama/Control_structures/select_statements.shtml Bash select statement].

2
Task/Menu/1META.yaml Normal file
View file

@ -0,0 +1,2 @@
---
note: Text processing

View file

@ -0,0 +1,28 @@
PROC menu select := (FLEX[]STRING items, UNION(STRING, VOID) prompt)STRING:
(
INT choice;
IF LWB items <= UPB items THEN
WHILE
FOR i FROM LWB items TO UPB items DO
printf(($g(0)") "gl$, i, items[i]))
OD;
CASE prompt IN
(STRING prompt):printf(($g" "$, prompt)),
(VOID):printf($"Choice ? "$)
ESAC;
read((choice, new line));
# WHILE # 1 > choice OR choice > UPB items
DO SKIP OD;
items[choice]
ELSE
""
FI
);
test:(
FLEX[0]STRING items := ("fee fie", "huff and puff", "mirror mirror", "tick tock");
STRING prompt := "Which is from the three pigs : ";
printf(($"You chose "g"."l$, menu select(items, prompt)))
)

22
Task/Menu/AWK/menu.awk Normal file
View file

@ -0,0 +1,22 @@
# syntax: GAWK -f MENU.AWK
BEGIN {
n = split("fee fie:huff and puff:mirror mirror:tick tock",arr,":")
while (1) {
print("")
for (i=1; i<=n; i++) {
printf("%d - %s\n",i,arr[i])
}
print("0 - exit")
printf("enter number: ")
getline ans
if (ans in arr) {
printf("you picked '%s'\n",arr[ans])
continue
}
if (ans == 0) {
break
}
print("invalid choice")
}
exit(0)
}

61
Task/Menu/Ada/menu-1.ada Normal file
View file

@ -0,0 +1,61 @@
-- menu2.adb --
-- rosetta.org menu example
-- GPS 4.3-5 (Debian)
-- note: the use of Unbounded strings is somewhat overkill, except that
-- it allows Ada to handle variable length string data easily
-- ie: differing length menu items text
with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Strings.Unbounded,
Ada.Strings.Unbounded.Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO,
Ada.Strings.Unbounded, Ada.Strings.Unbounded.Text_IO;
procedure menu2 is
package tio renames Ada.Integer_Text_IO;
-- rename package to use a shorter name, tio, as integer get prefix
menu_item : array (1..4) of Unbounded_String;
-- 4 menu items of any length
choice : integer := 0;
-- user selection entry value
procedure show_menu is
-- display the menu options and collect the users input
-- into locally global variable 'choice'
begin
for pntr in menu_item'first .. menu_item'last loop
put (pntr ); put(" "); put( menu_item(pntr)); new_line;
end loop;
put("chose (0 to exit) #:"); tio.get(choice);
end show_menu;
-- main program --
begin
menu_item(1) := to_unbounded_string("Fee Fie");
menu_item(2) := to_unbounded_string("Huff & Puff");
menu_item(3) := to_unbounded_string("mirror mirror");
menu_item(4) := to_unbounded_string("tick tock");
-- setup menu selection strings in an array
show_menu;
loop
if choice in menu_item'range then
put("you chose #:");
case choice is
-- in a real menu, each case would execute appropriate user procedures
when 1 => put ( menu_item(choice)); new_line;
when 2 => put ( menu_item(choice)); new_line;
when 3 => put ( menu_item(choice)); new_line;
when 4 => put ( menu_item(choice)); new_line;
when others => null;
end case;
show_menu;
else
put("Menu selection out of range"); new_line;
if choice = 0 then exit; end if;
-- need a exit option !
show_menu;
end if;
end loop;
end menu2;

20
Task/Menu/Ada/menu-2.ada Normal file
View file

@ -0,0 +1,20 @@
./menu2
1 Fee Fie
2 Huff & Puff
3 mirror mirror
4 tick tock
chose (0 to exit) #:2
you chose #:Huff & Puff
1 Fee Fie
2 Huff & Puff
3 mirror mirror
4 tick tock
chose (0 to exit) #:55
Menu selection out of range
1 Fee Fie
2 Huff & Puff
3 mirror mirror
4 tick tock
chose (0 to exit) #:0
Menu selection out of range
[2010-06-09 22:18:25] process terminated successfully (elapsed time: 15.27s)

View file

@ -0,0 +1,31 @@
GoSub, CreateGUI
return
Submit:
Gui, Submit, NoHide
If Input =
GuiControl,,Output
Else If Input not between 1 and 4
{
Gui, Destroy
Sleep, 500
GoSub, CreateGUI
}
Else {
GuiControlGet, string,,Text%Input%
GuiControl,,Output,% SubStr(string,4)
}
return
CreateGUI:
list = fee fie,huff and puff,mirror mirror,tick tock
Loop, Parse, list, `,
Gui, Add, Text, vText%A_Index%, %A_Index%: %A_LoopField%
Gui, Add, Text, ym, Which is from the three pigs?
Gui, Add, Edit, vInput gSubmit
Gui, Add, Edit, vOutput
Gui, Show
return
GuiClose:
ExitApp

12
Task/Menu/BASIC/menu.bas Normal file
View file

@ -0,0 +1,12 @@
function sel$(choices$(), prompt$)
if ubound(choices$) - lbound(choices$) = 0 then sel$ = ""
ret$ = ""
do
for i = lbound(choices$) to ubound(choices$)
print i; ": "; choices$(i)
next i
input ;prompt$, index
if index <= ubound(choices$) and index >= lbound(choices$) then ret$ = choices$(index)
while ret$ = ""
sel$ = ret$
end function

View file

@ -0,0 +1,21 @@
DIM list$(4)
list$() = "fee fie", "huff and puff", "mirror mirror", "tick tock"
selected$ = FNmenu(list$(), "Please make a selection: ")
PRINT selected$
END
DEF FNmenu(list$(), prompt$)
LOCAL index%, select$
IF SUM(list$()) = "" THEN = ""
REPEAT
CLS
FOR index% = 0 TO DIM(list$() ,1)
IF list$(index%)<>"" PRINT ; index% ":", list$(index%)
NEXT
PRINT prompt$ ;
INPUT "" select$
index% = VAL(select$)
IF select$<>STR$(index%) index% = -1
IF index%>=0 IF index%<=DIM(list$() ,1) IF list$(index%)="" index% = -1
UNTIL index%>=0 AND index%<=DIM(list$(), 1)
= list$(index%)

21
Task/Menu/Brat/menu.brat Normal file
View file

@ -0,0 +1,21 @@
menu = { prompt, choices |
true? choices.empty?
{ "" }
{
choices.each_with_index { c, i |
p "#{i}. #{c}"
}
selection = ask prompt
true? selection.numeric?
{ selection = selection.to_i
true? selection < 0 || { selection >= choices.length }
{ p "Selection is out of range"; menu prompt, choices }
{ choices[selection] }
}
{ p "Selection must be a number"; menu prompt, choices }
}
}
p menu "Selection: " ["fee fie" "huff and puff" "mirror mirror" "tick tock"]

50
Task/Menu/C++/menu.cpp Normal file
View file

@ -0,0 +1,50 @@
#include <iostream>
#include <boost/regex.hpp>
#include <cstdlib>
#include <string>
using namespace std;
void printMenu(const string *, int);
//checks whether entered data is in required range
bool checkEntry(string, const string *, int);
string dataEntry(string prompt, const string *terms, int size) {
if (size == 0) { //we return an empty string when we call the function with an empty list
return "";
}
string entry;
do {
printMenu(terms, size);
cout << prompt;
cin >> entry;
}
while( !checkEntry(entry, terms, size) );
int number = atoi(entry.c_str());
return terms[number - 1];
}
void printMenu(const string *terms, int num) {
for (int i = 1 ; i < num + 1 ; i++) {
cout << i << ')' << terms[ i - 1 ] << '\n';
}
}
bool checkEntry(string myEntry, const string *terms, int num) {
boost::regex e("^\\d+$");
if (!boost::regex_match(myEntry, e))
return false;
int number = atoi(myEntry.c_str());
if (number < 1 || number > num)
return false;
return true;
}
int main( ) {
const string terms[ ] = { "fee fie" , "huff and puff" , "mirror mirror" , "tick tock" };
int size = sizeof terms / sizeof *terms;
cout << "You chose: " << dataEntry("Which is from the three pigs: ", terms, size);
return 0;
}

25
Task/Menu/C-sharp/menu.cs Normal file
View file

@ -0,0 +1,25 @@
static void Main(string[] args)
{
List<string> menu_items = new List<string>() { "fee fie", "huff and puff", "mirror mirror", "tick tock" };
//List<string> menu_items = new List<string>();
Console.WriteLine(PrintMenu(menu_items));
Console.ReadLine();
}
private static string PrintMenu(List<string> items)
{
if (items.Count == 0)
return "";
string input = "";
int i = -1;
do
{
for (int j = 0; j < items.Count; j++)
Console.WriteLine("{0}) {1}", j, items[j]);
Console.WriteLine("What number?");
input = Console.ReadLine();
} while (!int.TryParse(input, out i) || i >= items.Count || i < 0);
return items[i];
}

44
Task/Menu/C/menu.c Normal file
View file

@ -0,0 +1,44 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char *menu_select(const char *const *items, const char *prompt);
int
main(void)
{
const char *items[] = {"fee fie", "huff and puff", "mirror mirror", "tick tock", NULL};
const char *prompt = "Which is from the three pigs?";
printf("You chose %s.\n", menu_select(items, prompt));
return EXIT_SUCCESS;
}
const char *
menu_select(const char *const *items, const char *prompt)
{
char buf[BUFSIZ];
int i;
int choice;
int choice_max;
if (items == NULL)
return NULL;
do {
for (i = 0; items[i] != NULL; i++) {
printf("%d) %s\n", i + 1, items[i]);
}
choice_max = i;
if (prompt != NULL)
printf("%s ", prompt);
else
printf("Choice? ");
if (fgets(buf, sizeof(buf), stdin) != NULL) {
choice = atoi(buf);
}
} while (1 > choice || choice > choice_max);
return items[choice - 1];
}

View file

@ -0,0 +1,22 @@
(defn menu [prompt choices]
(if (empty? choices)
""
(let [menutxt (apply str (interleave
(iterate inc 1)
(map #(str \space % \newline) choices)))]
(println menutxt)
(print prompt)
(flush)
(let [index (read-string (read-line))]
; verify
(if (or (not (integer? index))
(> index (count choices))
(< index 1))
; try again
(recur prompt choices)
; ok
(nth choices (dec index)))))))
(println "You chose: "
(menu "Which is from the three pigs: "
["fee fie" "huff and puff" "mirror mirror" "tick tock"]))

View file

@ -0,0 +1,13 @@
(defun select (prompt choices)
(if (null choices)
""
(do (n)
((and n (<= 0 n (1- (length choices))))
(nth n choices))
(format t "~&~a~%" prompt)
(loop for n from 0
for c in choices
do (format t " ~d) ~a~%" n c))
(force-output)
(setf n (parse-integer (read-line *standard-input* nil)
:junk-allowed t)))))

34
Task/Menu/D/menu.d Normal file
View file

@ -0,0 +1,34 @@
import std.stdio, std.conv, std.string, std.array;
string menuSelect(in string[] entries) {
static int validChoice(in string input,
in int nEntries) pure nothrow {
try {
immutable n = to!int(input);
return (n >= 0 && n <= nEntries) ? n : -1;
} catch (Exception e) // very generic
return -1; // not valid
}
if (entries.empty)
return "";
while (true) {
writeln("Choose one:");
foreach (i, const string entry; entries)
writefln(" %d) %s", i, entry);
writef("> ");
immutable input = readln().chomp();
immutable choice = validChoice(input, entries.length-1);
if (choice != -1)
return entries[choice]; // we have a valid choice
else
writeln("Wrong choice.");
}
}
void main() {
immutable items = ["fee fie", "huff and puff",
"mirror mirror", "tick tock"];
writeln("You chose '", menuSelect(items), "'.");
}

View file

@ -0,0 +1,22 @@
include get.e
function menu_select(sequence items, object prompt)
if length(items) = 0 then
return ""
else
for i = 1 to length(items) do
printf(1,"%d) %s\n",{i,items[i]})
end for
if atom(prompt) then
prompt = "Choice?"
end if
return items[prompt_number(prompt,{1,length(items)})]
end if
end function
constant items = {"fee fie", "huff and puff", "mirror mirror", "tick tock"}
constant prompt = "Which is from the three pigs? "
printf(1,"You chose %s.\n",{menu_select(items,prompt)})

View file

@ -0,0 +1,12 @@
USE: formatting
: print-menu ( seq -- )
[ 1 + swap "%d - %s\n" printf ] each-index
"Your choice? " write flush ;
: select ( seq -- result )
dup print-menu
readln string>number [
1 - swap 2dup bounds-check?
[ nth ] [ nip select ] if
] [ select ] if* ;

View file

@ -0,0 +1,36 @@
class Main
{
static Void displayList (Str[] items)
{
items.each |Str item, Int index|
{
echo ("$index: $item")
}
}
public static Str getChoice (Str[] items)
{
selection := -1
while (selection == -1)
{
displayList (items)
Env.cur.out.print ("Select: ").flush
input := Int.fromStr(Env.cur.in.readLine, 10, false)
if (input != null)
{
if (input >= 0 && input < items.size)
{
selection = input
}
}
echo ("Try again")
}
return items[selection]
}
public static Void main ()
{
choice := getChoice (["fee fie", "huff and puff", "mirror mirror", "tick tock"])
echo ("You chose: $choice")
}
}

37
Task/Menu/Go/menu.go Normal file
View file

@ -0,0 +1,37 @@
package main
import "fmt"
func menu(choices []string, prompt string) string {
if len(choices) == 0 {
return ""
}
var c int
for {
fmt.Println("")
for i, s := range choices {
fmt.Printf("%d. %s\n", i+1, s)
}
fmt.Print(prompt)
_, err := fmt.Scanln(&c)
if err == nil && c > 0 && c <= len(choices) {
break
}
}
return choices[c-1]
}
func main() {
pick := menu(nil, "No prompt")
fmt.Printf("No choices, result = %q\n", pick)
choices := []string{
"fee fie",
"huff and puff",
"mirror mirror",
"tick tock",
}
pick = menu(choices, "Enter number: ")
fmt.Printf("You picked %q\n", pick)
}

View file

@ -0,0 +1,24 @@
module RosettaSelect where
import Data.Maybe (listToMaybe)
import Control.Monad (guard)
select :: [String] -> IO String
select [] = return ""
select menu = do
putStr $ showMenu menu
putStr "Choose an item: "
choice <- getLine
maybe (select menu) return $ choose menu choice
showMenu :: [String] -> String
showMenu menu = unlines [show n ++ ") " ++ item | (n, item) <- zip [1..] menu]
choose :: [String] -> String -> Maybe String
choose menu choice = do
n <- maybeRead choice
guard $ n > 0
listToMaybe $ drop (n-1) menu
maybeRead :: Read a => String -> Maybe a
maybeRead = fmap fst . listToMaybe . filter (null . snd) . reads

View file

@ -0,0 +1,8 @@
*RosettaSelect> select ["fee fie", "huff and puff", "mirror mirror", "tick tock"]
1) fee fie
2) huff and puff
3) mirror mirror
4) tick tock
Choose an item: 3
"mirror mirror"
*RosettaSelect>

View file

@ -0,0 +1,9 @@
CHARACTER list = "fee fie,huff and puff,mirror mirror,tick tock,", answer*20
POP(Menu=list, SelTxt=answer)
SUBROUTINE list ! callback procedure must have same name as menu argument
! Subroutine with no arguments: all objects are global
! The global variable $$ returns the selected list index
WRITE(Messagebox, Name) answer, $$
END

13
Task/Menu/Icon/menu.icon Normal file
View file

@ -0,0 +1,13 @@
procedure main()
L := ["fee fie", "huff and puff", "mirror mirror", "tick tock"]
every i := 1 to *L do
write(i,") ",L[i])
repeat {
writes("Choose a number from the menu above: ")
a := read()
if 1 <= integer(a) <= i then break
}
write("You selected ",a," ==> ",L[a])
end

6
Task/Menu/J/menu-1.j Normal file
View file

@ -0,0 +1,6 @@
require'misc'
showMenu =: i.@# smoutput@,&":&> ' '&,&.>
makeMsg =: 'Choose a number 0..' , ': ',~ ":@<:@#
errorMsg =: [ smoutput bind 'Please choose a valid number!'
select=: ({::~ _&".@prompt@(makeMsg [ showMenu)) :: ($:@errorMsg)

1
Task/Menu/J/menu-2.j Normal file
View file

@ -0,0 +1 @@
select 'fee fie'; 'huff and puff'; 'mirror mirror'; 'tick tock'

16
Task/Menu/Java/menu.java Normal file
View file

@ -0,0 +1,16 @@
public static String select(List<String> list, String prompt){
if(list.size() == 0) return "";
Scanner sc = new Scanner(System.in);
String ret = null;
do{
for(int i=0;i<list.size();i++){
System.out.println(i + ": "+list.get(i));
}
System.out.print(prompt);
int index = sc.nextInt();
if(index >= 0 && index < list.size()){
ret = list.get(index);
}
}while(ret == null);
return ret;
}

View file

@ -0,0 +1,20 @@
function select(question, choices) {
var prompt = "";
for (var i in choices)
prompt += i + ". " + choices[i] + "\n";
prompt += question;
var input;
while (1) {
WScript.Echo(prompt);
input = parseInt( WScript.StdIn.readLine() );
if (0 <= input && input < choices.length)
break;
WScript.Echo("\nTry again.");
}
return input;
}
var choices = ['fee fie', 'huff and puff', 'mirror mirror', 'tick tock'];
var choice = select("Which is from the three pigs?", choices);
WScript.Echo("you selected: " + choice + " -> " + choices[choice]);

13
Task/Menu/Logo/menu.logo Normal file
View file

@ -0,0 +1,13 @@
to select :prompt [:options]
foreach :options [(print # ?)]
forever [
type :prompt type "| |
make "n readword
if (and [number? :n] [:n >= 1] [:n <= count :options]) [output item :n :options]
print sentence [Must enter a number between 1 and] count :options
]
end
print equal? [huff and puff] (select
[Which is from the three pigs?]
[fee fie] [huff and puff] [mirror mirror] [tick tock])

12
Task/Menu/Lua/menu.lua Normal file
View file

@ -0,0 +1,12 @@
function choice(choices)
for i, v in ipairs(choices) do print(i, v) end
print"Enter your choice"
local selection = io.read() + 0
if choices[selection] then print(choices[selection])
else choice(choices)
end
end
choice{"fee fie", "huff and puff", "mirror mirror", "tick tock"}

38
Task/Menu/MATLAB/menu.m Normal file
View file

@ -0,0 +1,38 @@
function sucess = menu(list)
if numel(list) == 0
sucess = '';
return
end
while(true)
disp('Please select one of these options:');
for i = (1:numel(list))
disp([num2str(i) ') ' list{i}]);
end
disp([num2str(numel(list)+1) ') exit']);
try
key = input(':: ');
if key == numel(list)+1
break
elseif (key > numel(list)) || (key < 0)
continue
else
disp(['-> ' list{key}]);
end
catch
continue
end
end
sucess = true;
end

View file

@ -0,0 +1,15 @@
MENU(STRINGS,SEP)
;http://rosettacode.org/wiki/Menu
NEW I,A,MAX
;I is a loop variable
;A is the string read in from the user
;MAX is the number of substrings in the STRINGS list
;SET STRINGS="fee fie^huff and puff^mirror mirror^tick tock"
SET MAX=$LENGTH(STRINGS,SEP)
QUIT:MAX=0 ""
WRITEMENU
FOR I=1:1:MAX WRITE I,": ",$PIECE(STRINGS,SEP,I),!
READ:30 !,"Choose a string by its index: ",A,!
IF (A<1)!(A>MAX)!(A\1'=A) GOTO WRITEMENU
KILL I,MAX
QUIT $PIECE(STRINGS,SEP,A)

View file

@ -0,0 +1,4 @@
textMenu[data_List] := (MapIndexed[Print[#2[[1]], ") ", #] &, {a, b, c}];
While[! (IntegerQ[choice] && Length[data] > choice > 0),
choice = Input["Enter selection"]];
data[[choice]])

View file

@ -0,0 +1,38 @@
MODULE Menu;
FROM InOut IMPORT WriteString, WriteCard, WriteLn, ReadCard;
CONST StringLength = 100;
MenuSize = 4;
TYPE String = ARRAY[0..StringLength-1] OF CHAR;
VAR menu : ARRAY[0..MenuSize] OF String;
selection, index : CARDINAL;
BEGIN
menu[1] := "fee fie";
menu[2] := "huff and puff";
menu[3] := "mirror mirror";
menu[4] := "tick tock";
FOR index := 1 TO HIGH(menu) DO
WriteString("[");
WriteCard( index,1);
WriteString( "] ");
WriteString( menu[index]);
WriteLn;
END;(*of FOR*)
WriteString("Choose what you want : ");
ReadCard(selection);
IF (selection <= HIGH(menu)) AND (selection > 0) THEN
WriteString("You have chosen: ");
WriteString( menu[selection]);
WriteLn;
ELSE
WriteString("Selection is out of range!");
WriteLn;
END (*of IF*)
END Menu.

15
Task/Menu/PHP/menu.php Normal file
View file

@ -0,0 +1,15 @@
<?php
$stdin = fopen("php://stdin", "r");
$allowed = array(1 => 'fee fie', 'huff and puff', 'mirror mirror', 'tick tock');
for(;;) {
foreach ($allowed as $id => $name) {
echo " $id: $name\n";
}
echo "Which is from the four pigs: ";
$stdin_string = fgets($stdin, 4096);
if (isset($allowed[(int) $stdin_string])) {
echo "You chose: {$allowed[(int) $stdin_string]}\n";
break;
}
}

18
Task/Menu/Perl/menu.pl Normal file
View file

@ -0,0 +1,18 @@
sub menu
{
my ($prompt,@array) = @_;
return '' unless @array;
print " $_: $array[$_]\n" for(0..$#array);
print $prompt;
$n = <>;
return $array[$n] if $n =~ /^\d+$/ and defined $array[$n];
return &menu($prompt,@array);
}
@a = ('fee fie', 'huff and puff', 'mirror mirror', 'tick tock');
$prompt = 'Which is from the three pigs: ';
$a = &menu($prompt,@a);
print "You chose: $a\n";

11
Task/Menu/PicoLisp/menu.l Normal file
View file

@ -0,0 +1,11 @@
(de choose (Prompt Items)
(use N
(loop
(for (I . Item) Items
(prinl I ": " Item) )
(prin Prompt " ")
(NIL (setq N (in NIL (read))))
(T (>= (length Items) N 1) (get Items N)) ) ) )
(choose "Which is from the three pigs?"
'("fee fie" "huff and puff" "mirror mirror" "tick tock") )

26
Task/Menu/Python/menu.py Normal file
View file

@ -0,0 +1,26 @@
def _menu(items):
for indexitem in enumerate(items):
print (" %2i) %s" % indexitem)
def _ok(reply, itemcount):
try:
n = int(reply)
return 0 <= n < itemcount
except:
return False
def selector(items, prompt):
'Prompt to select an item from the items'
if not items: return ''
reply = -1
itemcount = len(items)
while not _ok(reply, itemcount):
_menu(items)
# Use input instead of raw_input for Python 3.x
reply = raw_input(prompt).strip()
return items[int(reply)]
if __name__ == '__main__':
items = ['fee fie', 'huff and puff', 'mirror mirror', 'tick tock']
item = selector(items, 'Which is from the three pigs: ')
print ("You chose: " + item)

7
Task/Menu/R/menu.r Normal file
View file

@ -0,0 +1,7 @@
showmenu <- function()
{
choices <- c("fee fie", "huff and puff", "mirror mirror", "tick tock")
ans <- menu(choices)
if(ans==0) "" else choices[ans]
}
str <- showmenu()

38
Task/Menu/REXX/menu.rexx Normal file
View file

@ -0,0 +1,38 @@
/*REXX program shows a list, asks user for a selection number (integer).*/
do forever /*keep asking until response OK. */
call list_create /*create the list from scratch. */
call list_show /*display (show) the list to user*/
if #==0 then return '' /*if empty list, then return null*/
say right(' choose an item by entering a number from 1 ' #, 70, '')
parse pull x /*get the user's choice (if any).*/
select
when x='' then call sayErr "a choice wasn't entered"
when words(x)\==1 then call sayErr 'too many choices entered:'
when \datatype(x,'N') then call sayErr "the choice isn't numeric:"
when \datatype(x,'W') then call sayErr "the choice isn't an integer:"
when x<1 | x># then call sayErr "the choice isn't within range:"
otherwise leave /*this leaves the DO FOREVER loop*/
end /*select*/
end /*forever*/
/*user might've entered 2. or 003*/
x=x/1 /*normalize the number (maybe). */
say; say 'you chose item' x": " #.x
return #.x /*stick a fork in it, we're done.*/
/*──────────────────────────────────LIST_CREATE─────────────────────────*/
list_create: #.1='fee fie' /*one method for list-building. */
#.2='huff and puff'
#.3='mirror mirror'
#.4='tick tock'
#=4 /*store number of choices in #. */
return /*(above) is just one convention.*/
/*──────────────────────────────────LIST_SHOW───────────────────────────*/
list_show: say /*display a blank line. */
do j=1 for # /*display the list of choices. */
say '[item' j"] " #.j /*display item # with its choice.*/
end /*j*/
say /*display another blank line. */
return
/*──────────────────────────────────SAYERR──────────────────────────────*/
sayErr: say; say '***error!***' arg(1) x; say; return

23
Task/Menu/Ruby/menu.rb Normal file
View file

@ -0,0 +1,23 @@
def select(prompt, items)
return "" if items.length == 0
while true
items.each_index {|i| puts "#{i}. #{items[i]}"}
print "#{prompt}: "
begin
answer = Integer(gets())
rescue ArgumentError
redo
end
return items[answer] if answer.between?(0, items.length - 1)
end
end
# test empty list
response = select("Which is empty", [])
puts "empty list returns: >#{response}<"
puts ""
# "real" test
items = ['fee fie', 'huff and puff', 'mirror mirror', 'tick tock']
response = select("Which is from the three pigs", items)
puts "you chose: >#{response}<"

20
Task/Menu/Tcl/menu-1.tcl Normal file
View file

@ -0,0 +1,20 @@
proc select {prompt choices} {
set nc [llength $choices]
if {!$nc} {
return ""
}
set numWidth [string length $nc]
while true {
set i 0
foreach s $choices {
puts [format " %-*d: %s" $numWidth [incr 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]
}
}
}

31
Task/Menu/Tcl/menu-2.tcl Normal file
View file

@ -0,0 +1,31 @@
% puts >[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<