Menu: Difference between revisions

34,300 bytes added ,  1 month ago
(Pascal example corrected: return empty string if list empty)
(119 intermediate revisions by 54 users not shown)
Line 19:
;Note:
This task is fashioned after the action of the [http://www.softpanorama.org/Scripting/Shellorama/Control_structures/select_statements.shtml Bash select statement].
<br><br>
 
=={{header|Ada11l}}==
<syntaxhighlight lang="11l">V items = [‘fee fie’, ‘huff and puff’, ‘mirror mirror’, ‘tick tock’]
<lang Ada>
-- menu2.adb --
-- rosetta.org menu example
-- GPS 4.3-5 (Debian)
 
L
-- note: the use of Unbounded strings is somewhat overkill, except that
L(item) items
-- it allows Ada to handle variable length string data easily
print(‘#2. #.’.format(L.index + 1, item))
-- ie: differing length menu items text
with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Strings.Unbounded,
Ada.Strings.Unbounded.Text_IO;
 
V reply = input(‘Which is from the three pigs: ’).trim(‘ ’)
use Ada.Text_IO, Ada.Integer_Text_IO,
I !reply.is_digit()
Ada.Strings.Unbounded, Ada.Strings.Unbounded.Text_IO;
L.continue
 
I Int(reply) C 1..items.len
procedure menu2 is
print(‘You chose: ’items[Int(reply) - 1])
package tio renames Ada.Integer_Text_IO;
L.break</syntaxhighlight>
-- 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
 
{{out}}
procedure show_menu is
<pre>
-- display the menu options and collect the users input
1. fee fie
-- into locally global variable 'choice'
2. huff and puff
begin
3. mirror mirror
for pntr in menu_item'first .. menu_item'last loop
4. tick tock
put (pntr ); put(" "); put( menu_item(pntr)); new_line;
Which is from the three pigs: a
end loop;
1. fee fie
put("chose (0 to exit) #:"); tio.get(choice);
2. huff and puff
end show_menu;
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: 2
You chose: huff and puff
</pre>
 
=={{header|Action!}}==
-- main program --
<syntaxhighlight lang="action!">DEFINE PTR="CARD"
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;
 
BYTE FUNC Init(PTR ARRAY items)
loop
items(0)="fee fie"
if choice in menu_item'range then
putitems(1)="youhuff choseand #:puff");
items(2)="mirror mirror"
case choice is
items(3)="tick tock"
-- in a real menu, each case would execute appropriate user procedures
RETURN (4)
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;
 
PROC ShowMenu(PTR ARRAY items BYTE count)
end menu2;
BYTE i
FOR i=1 TO count
DO
PrintF("(%B) %S%E",i,items(i-1))
OD
RETURN
 
BYTE FUNC GetMenuItem(PTR ARRAY items BYTE count)
</lang>
BYTE res
DO
ShowMenu(items,count) PutE()
Print("Make your choise: ")
res=InputB()
UNTIL res>=1 AND res<=count
OD
RETURN (res-1)
 
PROC Main()
<lang Ada>
PTR ARRAY items(10)
./menu2
BYTE count,res
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)
 
count=Init(items)
</lang>
res=GetMenuItem(items,count)
PrintF("You have chosen: %S%E",items(res))
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Menu.png Screenshot from Atari 8-bit computer]
<pre>
(1) fee fie
(2) huff and puff
(3) mirror mirror
(4) tick tock
 
Make your choise: 5
(1) fee fie
(2) huff and puff
(3) mirror mirror
(4) tick tock
 
Make your choise: 2
You have chosen: huff and puff
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with ada.text_io,Ada.Strings.Unbounded; use ada.text_io, Ada.Strings.Unbounded;
 
procedure menu is
type menu_strings is array (positive range <>) of Unbounded_String ;
function "+" (s : string) return Unbounded_String is (To_Unbounded_String (s));
 
function choice (m : menu_strings; prompt : string) return string is
begin
if m'length > 0 then
loop
put_line (prompt);
for i in m'range loop
put_line (i'img &") " & To_String (m(i)));
end loop;
begin
return To_String (m(positive'value (get_line)));
exception when others => put_line ("Try again !");
end;
end loop;
end if;
return "";
end choice;
 
begin
put_line ("You chose " &
choice ((+"fee fie",+"huff and puff",+"mirror mirror",+"tick tock"),"Enter your choice "));
end menu;</syntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 118 ⟶ 147:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''}}
<langsyntaxhighlight lang="algol68">PROC menu select := (FLEX[]STRING items, UNION(STRING, VOID) prompt)STRING:
(
INT choice;
Line 145 ⟶ 174:
 
printf(($"You chose "g"."l$, menu select(items, prompt)))
)</langsyntaxhighlight>
Output:
<pre>
Line 156 ⟶ 185:
</pre>
 
=={{header|AutoHotkeyArturo}}==
<syntaxhighlight lang="rebol">menu: function [items][
<lang autohotkey>GoSub, CreateGUI
selection: neg 1
return
while [not? in? selection 1..size items][
loop.with:'i items 'item -> print ~"|i+1|. |item|"
inp: input "Enter a number: "
if numeric? inp ->
selection: to :integer inp
]
print items\[selection-1]
]
 
menu ["fee fie" "huff and puff" "mirror mirror" "tick tock"]</syntaxhighlight>
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
 
{{out}}
CreateGUI:
 
list = fee fie,huff and puff,mirror mirror,tick tock
<pre>1. fee fie
Loop, Parse, list, `,
2. huff and puff
Gui, Add, Text, vText%A_Index%, %A_Index%: %A_LoopField%
3. mirror mirror
Gui, Add, Text, ym, Which is from the three pigs?
4. tick tock
Gui, Add, Edit, vInput gSubmit
Enter a number: something wrong
Gui, Add, Edit, vOutput
1. fee fie
Gui, Show
2. huff and puff
return
3. mirror mirror
4. tick tock
Enter a number: 5
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
Enter a number: 3
mirror mirror</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">Menu(list:=""){
if !list ; if called with an empty list
return ; return an empty string
for i, v in x := StrSplit(list, "`n", "`r")
string .= (string?"`n":"") i "- " v
, len := StrLen(v) > len ? StrLen(v) : len
while !x[Choice]
InputBox , Choice, Please Select From Menu, % string ,, % 200<len*7 ? 200 ? len*7 , % 120 + x.count()*20
return x[Choice]
}</syntaxhighlight>
Examples:<syntaxhighlight lang="autohotkey">list =
(
fee fie
huff and puff
mirror mirror
tick tock
)
MsgBox % Menu(list) ; call menu with list
MsgBox % Menu() ; call menu with empty list
return</syntaxhighlight>
 
GuiClose:
ExitApp</lang>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f MENU.AWK
BEGIN {
print("you picked:",menu(""))
n = split("fee fie:huff and puff:mirror mirror:tick tock",arr,":")
print("you picked:",menu("fee fie:huff and puff:mirror mirror:tick tock"))
exit(0)
}
function menu(str, ans,arr,i,n) {
if (str == "") {
return
}
n = split(str,arr,":")
while (1) {
print("")
Line 199 ⟶ 259:
printf("%d - %s\n",i,arr[i])
}
printprintf("0? - exit")
printf("enter number: ")
getline ans
if (ans in arr) {
printfreturn("you picked '%s'\n",arr[ans])
continue
}
if (ans == 0) {
break
}
print("invalid choice")
}
exit(0)
}
</syntaxhighlight>
</lang>
 
=={{header|Axe}}==
{{incorrect|Axe|The function should return an empty string if called with an empty list. Please also check if this could really used as a [https://en.wikipedia.org/wiki/Subroutine function aka subroutine.]}}
In Axe, static data (such as strings) is laid out sequentially in memory. So the H in "HUFF" is the byte after the null terminator for "FIE". However, null terminators are only added to strings when they are stored with the store symbol →. strGet returns a pointer to the start of the nth null-terminated string in the data, which is why the strings must be laid out in memory correctly.
<langsyntaxhighlight lang="axe">"FEE FIE"→Str1
"HUFF AND PUFF"→Str2
"MIRROR MIRROR"→Str3
Line 231 ⟶ 286:
Return
End
Disp strGet(Str1,N-1),i</langsyntaxhighlight>
 
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
<langsyntaxhighlight lang="qbasic"> function sel$(choices$(), prompt$)
if ubound(choices$) - lbound(choices$) = 0 then sel$ = ""
ret$ = ""
Line 246 ⟶ 301:
while ret$ = ""
sel$ = ret$
end function</langsyntaxhighlight>
 
 
==={{header|Applesoft BASIC}}===
While the following example could be lengthened to demonstrate larger menu-driven projects, it is useful to simply print the resulting string indexed by the user input.
<syntaxhighlight lang="applessoftbasic"> 10 M$(4) = "TICK TOCK"
20 M$(3) = "MIRROR MIRROR"
30 M$(2) = "HUFF AND PUFF"
40 M$(1) = "FEE FIE"
50 GOSUB 100"MENU
60 PRINT M$
70 END
100 M$ = ""
110 FOR M = 0 TO 1 STEP 0
120 FOR N = 1 TO 1E9
130 IF LEN (M$(N)) THEN PRINT N". "M$(N): NEXT N
140 IF N = 1 THEN RETURN
150 INPUT "ENTER A NUMBER:";N%
160 M = N% > = 1 AND N% < N
170 NEXT M
180 M$ = M$(N%)
190 RETURN </syntaxhighlight>
 
==={{header|Commodore BASIC}}===
 
While the following example could be shortened to simply print the resulting string indexed by the user input, it is useful to demonstrate that larger menu-driven projects benefit from the use of the <code>ON n... GOSUB</code> statement to pass control to larger subroutines.
 
<syntaxhighlight lang="commodorebasic">1 rem menu
5 rem rosetta code
10 gosub 900
 
20 print chr$(147);chr$(14)
30 print " Menu "
35 print:print "Choose an incantation:":print
40 for i=1 to 5
45 print i;chr$(157);". ";op$(i,1)
50 next i:print
55 print "choose one: ";
60 get k$:if k$<"1" or k$>"5" then 60
65 k=val(k$):print chr$(147)
70 on k gosub 100,200,300,400,500
80 if k=5 then end
 
90 print:print "Press any key to continue."
95 get k$:if k$="" then 95
96 goto 20
 
100 rem fee fi
110 print op$(k,2)
115 return
 
200 rem huff puff
210 print op$(k,2)
215 return
 
300 rem mirror mirror
310 print op$(k,2)
315 return
 
400 rem tick tock
410 print op$(k,2)
415 return
 
500 rem quit
510 print op$(k,2):print "Goodbye!"
515 return
 
900 rem initialize
905 dim op$(10,2)
910 for a=1 to 5
915 read op$(a,1),op$(a,2)
920 next a
925 return
 
1000 data "Fee fi fo fum","I smell the blood of an Englishman!"
1005 data "Huff and puff","The house blew down!"
1010 data "Mirror, mirror","You seem to be the fairest of them all!"
1015 data "Tick tock","Time passes..."
1020 data "<Quit>","You decide to leave."</syntaxhighlight>
 
=={{header|Batch File}}==
Example 1
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off & setlocal enabledelayedexpansion
 
set "menuChoices="fee fie","huff and puff","mirror mirror","tick tock""
::The Main Thing...
set choices="fee fie","huff and puff","mirror mirror","tick tock"
set "quest=Which is from the three pigs?"
call :select
pause>nul
exit /b 0
::/The Main Thing.
 
call :menu
::The Function...
 
:select
pause>nul & exit
set number=0
 
for %%A in (%choices%) do set tmpvar=%%A&set /a number+=1&set opt!number!=!tmpvar:"=!
 
:menu
if defined menuChoices (
set "counter=0" & for %%a in (%menuChoices%) do (
set /a "counter+=1"
set "currentMenuChoice=%%a"
set option[!counter!]=!currentMenuChoice:"=!
)
)
:tryagain
cls&echo.
for /l %%Aa in (1,1,%numbercounter%) do echo. Option %%A -a^) !optoption[%%Aa]!
echo.
set /p "input=Choice 1-%questcounter%: "
echo.
for /l %%A in (1,1,%number%) do (
for /l %%a in (1,1,%counter%) do (
if !input! equ %%A echo.&echo.You chose option %%A - !opt%%A!&goto :EOF
if !input! equ %%a echo You chose [ %%a^) !option[%%a]! ] & goto :EOF
)
echo.
echo.Invalid Input. Please try again...
pause
goto :tryagain</syntaxhighlight>
Example 2
<syntaxhighlight lang="dos">
@echo off
 
call:menu "fee fie" "huff and puff" "mirror mirror" "tick tock"
pause>nul
exit /b
goto tryagain
 
::/The Function.</lang>
:menu
cls
setlocal enabledelayedexpansion
set count=0
set reset=endlocal ^& goto menu
:menuloop
for %%i in (%*) do (
set /a count+=1
set string[!count!]=%%~i
echo string[!count!] = %%~i
)
echo.
set /p choice=^>
if "%choice%"=="" %reset%
set "isNum="
for /f "delims=0123456789" %%i in ("%choice%") do set isNum=%%i
if defined isNum %reset%
if %choice% gtr %count% %reset%
echo.!string[%choice%]!
goto:eof
</syntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> DIM list$(4)
list$() = "fee fie", "huff and puff", "mirror mirror", "tick tock"
selected$ = FNmenu(list$(), "Please make a selection: ")
Line 299 ⟶ 464:
IF index%>=0 IF index%<=DIM(list$() ,1) IF list$(index%)="" index% = -1
UNTIL index%>=0 AND index%<=DIM(list$(), 1)
= list$(index%)</langsyntaxhighlight>
Empty entries in the list are not offered as options, nor accepted as a selection.
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">menu = { prompt, choices |
true? choices.empty?
{ "" }
Line 323 ⟶ 488:
}
 
p menu "Selection: " ["fee fie" "huff and puff" "mirror mirror" "tick tock"]</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 369 ⟶ 534:
 
return items[choice - 1];
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<syntaxhighlight lang="csharp">
using System;
using System.Collections.Generic;
 
public class Menu
{
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];
}
}
</syntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <vector>
Line 421 ⟶ 621:
std::cout << "You chose: " << data_entry("> ", terms) << std::endl;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp}}==
<lang csharp>
using System;
using System.Collections.Generic;
 
public class Menu
{
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];
}
}
</lang>
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">"Run the module `menu`."
shared void run() {
value selection = menu("fee fie", "huff And puff", "mirror mirror", "tick tock");
Line 482 ⟶ 647:
}
 
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn menu [prompt choices]
(if (empty? choices)
""
Line 506 ⟶ 671:
(println "You chose: "
(menu "Which is from the three pigs: "
["fee fie" "huff and puff" "mirror mirror" "tick tock"]))</langsyntaxhighlight>
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Test-Prompt-Menu.
 
Line 600 ⟶ 765:
.
 
END PROGRAM Prompt-Menu.</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun select (prompt choices)
(if (null choices)
""
Line 615 ⟶ 780:
(force-output)
(setf n (parse-integer (read-line *standard-input* nil)
:junk-allowed t)))))</langsyntaxhighlight>
 
=={{header|D}}==
<syntaxhighlight lang="d">
<lang d>import std.stdio, std.conv, std.string, std.array, std.typecons;
import std.stdio, std.conv, std.string, std.array, std.typecons;
 
string menuSelect(in string[] entries) {
Line 626 ⟶ 792:
try {
immutable n = input.to!int;
 
return typeof(return)((n >= 0 && n <= nEntries) ? n : -1);
} catch (Exception e) // Very generic
Line 639 ⟶ 806:
writefln(" %d) %s", i, entry);
"> ".write;
 
immutable input = readln.chomp;
 
immutable choice = validChoice(input, entries.length - 1);
immutable choice = validChoice(input, cast(int) (entries.length - 1));
 
if (choice.isNull)
"Wrong choice.".writeln;
Line 651 ⟶ 821:
immutable items = ["fee fie", "huff and puff",
"mirror mirror", "tick tock"];
 
writeln("You chose '", items.menuSelect, "'.");
}
}</lang>
</syntaxhighlight>
 
{{out}}
<pre>Choose one:
Choose one:
0) fee fie
1) huff and puff
Line 660 ⟶ 834:
3) tick tock
> 2
You chose 'mirror mirror'.</pre>
</pre>
 
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
program Menu;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils;
 
function ChooseMenu(Options: TArray<string>; Prompt: string): string;
var
index: Integer;
value: string;
begin
if Length(Options) = 0 then
exit('');
repeat
writeln;
for var i := 0 to length(Options) - 1 do
writeln(i + 1, '. ', Options[i]);
write(#10, Prompt, ' ');
Readln(value);
index := StrToIntDef(value, -1);
until (index > 0) and (index <= length(Options));
Result := Options[index];
end;
 
begin
writeln('You picked ', ChooseMenu(['fee fie', 'huff and puff', 'mirror mirror',
'tick tock'], 'Enter number: '));
readln;
end.</syntaxhighlight>
{{out}}
<pre>
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
 
Enter number: 5
 
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
 
Enter number: 2
You picked huff and puff</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Menu do
def select(_, []), do: ""
def select(prompt, items) do
Line 683 ⟶ 909:
items = ["fee fie", "huff and puff", "mirror mirror", "tick tock"]
response = Menu.select("Which is from the three pigs", items)
IO.puts "you chose: #{inspect response}"</langsyntaxhighlight>
 
{{out}}
Line 702 ⟶ 928:
you chose: "tick tock"
</pre>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">
 
(let ((prompt-buffer-name "***** prompt *****")
(option-list '("fee fie"
"huff and puff"
"mirror mirror"
"tick tock"))
(extra-prompt-message "")
(is-selected nil)
(user-input-value nil))
 
;; Switch to an empty buffer
(switch-to-buffer-other-window prompt-buffer-name)
(read-only-mode -1)
(erase-buffer)
;; Display the options
(cl-loop for opt-idx from 1 to (length option-list) do
(insert (format "%d\) %s \n" opt-idx (nth (1- opt-idx) option-list))))
(while (not is-selected)
;; Read user input
(setq user-input-value (read-string (concat "select an option" extra-prompt-message " : ")))
(setq user-input-value (read user-input-value))
;; Validate user input
(if (and (fixnump user-input-value)
(<= user-input-value (length option-list))
(> user-input-value 0))
;; Display result
(progn
(end-of-buffer)
(insert (concat "\nYou selected: " (nth (1- user-input-value) option-list)))
(setq is-selected 't)
)
(progn
(setq extra-prompt-message " (please input a valid number)")
)
)
)
)
 
</syntaxhighlight>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROCEDURE Selection(choices$[],prompt$->sel$)
IF UBOUND(choices$,1)-LBOUND(choices$,1)=0 THEN
Line 721 ⟶ 990:
sel$=ret$
END PROCEDURE
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">include get.e
 
function menu_select(sequence items, object prompt)
Line 745 ⟶ 1,014:
constant prompt = "Which is from the three pigs? "
 
printf(1,"You chose %s.\n",{menu_select(items,prompt)})</langsyntaxhighlight>
 
=={{header|F Sharp|F#}}==
<syntaxhighlight lang="fsharp">open System
 
let rec menuChoice (options : string list) prompt =
if options = [] then ""
else
for i = 0 to options.Length - 1 do
printfn "%d. %s" (i + 1) options.[i]
 
printf "%s" prompt
let input = Int32.TryParse(Console.ReadLine())
 
match input with
| true, x when 1 <= x && x <= options.Length -> options.[x - 1]
| _, _ -> menuChoice options prompt
 
[<EntryPoint>]
let main _ =
let menuOptions = ["fee fie"; "huff and puff"; "mirror mirror"; "tick tock"]
let choice = menuChoice menuOptions "Choose one: "
printfn "You chose: %s" choice
 
0</syntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USEUSING: formatting io kernel math math.parser sequences ;
 
: print-menu ( seq -- )
Line 754 ⟶ 1,047:
"Your choice? " write flush ;
 
: (select) ( seq -- result )
dup print-menu readln string>number dup integer? [
drop 1 - swap 2dup bounds-check?
readln string>number [
1[ -nth swap] 2dup[ bounds-check?nip (select) ] if
[ nth ] [ nipdrop (select) ] if* ;
 
] [ select ] if* ;</lang>
: select ( seq -- result ) [ "" ] [ (select) ] if-empty ;</syntaxhighlight>
 
Example usage:
Line 773 ⟶ 1,067:
 
=={{header|Fantom}}==
{{incorrect|Fantom|The function should return an empty string if called with an empty list. Please also check if this could really used as a [https://en.wikipedia.org/wiki/Subroutine function aka subroutine.]}}
<lang fantom>class Main
<syntaxhighlight lang="fantom">class Main
{
static Void displayList (Str[] items)
Line 808 ⟶ 1,103:
echo ("You chose: $choice")
}
}</langsyntaxhighlight>
 
=={{header|Forth}}==
===Idiomatic Forth===
Out of the box Forth does not have lists. This version uses strings and a vector table, which arguably is more how one would do this task in Forth. It returns a nil string if a nil string is given otherwise the input string becomes the title of the menu.
<syntaxhighlight lang="forth">\ Rosetta Code Menu Idiomatic Forth
 
\ vector table compiler
: CASE: ( -- ) CREATE ;
: | ( -- <text>) ' , ; IMMEDIATE
: ;CASE ( -- ) DOES> SWAP CELLS + @ EXECUTE ;
 
: NIL ( -- addr len) S" " ;
: FEE ( -- addr len) S" fee fie" ;
: HUFF ( -- addr len) S" huff and puff" ;
: MIRROR ( -- addr len) S" mirror mirror" ;
: TICKTOCK ( -- addr len) S" tick tock" ;
 
CASE: SELECT ( n -- addr len)
| NIL | FEE | HUFF | MIRROR | TICKTOCK
;CASE
 
CHAR 1 CONSTANT '1'
CHAR 4 CONSTANT '4'
: BETWEEN ( n low hi -- ?) 1+ WITHIN ;
 
: MENU ( addr len -- addr len )
DUP 0=
IF
2DROP NIL EXIT
ELSE
BEGIN
CR
CR 2DUP 3 SPACES TYPE
CR ." 1 " 1 SELECT TYPE
CR ." 2 " 2 SELECT TYPE
CR ." 3 " 3 SELECT TYPE
CR ." 4 " 4 SELECT TYPE
CR ." Choice: " KEY DUP EMIT
DUP '1' '4' BETWEEN 0=
WHILE
DROP
REPEAT
-ROT 2DROP \ drop input string
CR [CHAR] 0 - SELECT
THEN
;</syntaxhighlight>
 
===If there must be lists===
Here we extend Forth to support simple lists and complete the task using the language extensions.
<syntaxhighlight lang="forth">\ Rosetta Menu task with Simple lists in Forth
 
: STRING, ( caddr len -- ) HERE OVER CHAR+ ALLOT PLACE ;
: " ( -- ) [CHAR] " PARSE STRING, ;
 
: { ( -- ) ALIGN 0 C, ;
: } ( -- ) { ;
 
: {NEXT} ( str -- next_str) COUNT + ;
: {NTH} ( n array_addr -- str) SWAP 0 DO {NEXT} LOOP ;
 
: {LEN} ( array_addr -- ) \ count strings in a list
0 >R \ Counter on Rstack
{NEXT} \ skip 1st empty string
BEGIN
{NEXT} DUP C@ \ Fetch length byte
WHILE \ While true
R> 1+ >R \ Inc. counter
REPEAT
DROP
R> ; \ return counter to data stack
 
: {TYPE} ( $ -- ) COUNT TYPE ;
: '"' ( -- ) [CHAR] " EMIT ;
: {""} ( $ -- ) '"' SPACE {TYPE} '"' SPACE ;
: }PRINT ( n array -- ) {NTH} {TYPE} ;
 
\ ===== TASK BEGINS =====
CREATE GOODLIST
{ " fee fie"
" huff and puff"
" mirror mirror"
" tick tock" }
 
CREATE NIL { }
 
CHAR 1 CONSTANT '1'
CHAR 4 CONSTANT '4'
CHAR 0 CONSTANT '0'
 
: BETWEEN ( n low hi -- ?) 1+ WITHIN ;
 
: .MENULN ( n -- n) DUP '0' + EMIT SPACE OVER }PRINT ;
 
: MENU ( list -- string )
DUP {LEN} 0=
IF
DROP NIL
ELSE
BEGIN
CR
CR 1 .MENULN
CR 2 .MENULN
CR 3 .MENULN
CR 4 .MENULN
CR ." Choice: " KEY DUP EMIT
DUP '1' '4' BETWEEN
0= WHILE
DROP
REPEAT
[CHAR] 0 -
CR SWAP {NTH}
THEN
;</syntaxhighlight>
 
Test at the gForth console
<PRE>GOODLIST MENU
 
1 fee fie
2 huff and puff
3 mirror mirror
4 tick tock
Choice: 0
 
1 fee fie
2 huff and puff
3 mirror mirror
4 tick tock
Choice: Q
 
1 fee fie
2 huff and puff
3 mirror mirror
4 tick tock
Choice: 2
ok
{TYPE} huff and puff ok
ok
NIL MENU ok
{TYPE} ok</PRE>
 
=={{header|Fortran}}==
 
Please find the example output along with the build instructions in the comments at the start of the FORTRAN 2008 source. Compiler: gfortran from the GNU compiler collection. Command interpreter: bash.
Please find the build instructions in the comments at the start of the FORTRAN 2008 source. Compiler: gfortran from the GNU compiler collection. Command interpreter: bash.
<lang FORTRAN>
<syntaxhighlight lang="fortran">
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Mon Jun 3 23:08:36
!
!a=./f && make $a && OMP_NUM_THREADS=2 $a
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
!
!$ ./f
! Choose fairly a tail
! 1: fee fie
! 2: huff and puff
! 3: mirror mirror
! 4: tick tock
!bad input
! Choose fairly a tail
! 1: fee fie
! 2: huff and puff
! 3: mirror mirror
! 4: tick tock
!^D
!
!STOP Unexpected end of file
!$ ./f
! Choose fairly a tail
! 1: fee fie
! 2: huff and puff
! 3: mirror mirror
! 4: tick tock
!88
! Choose fairly a tail
! 1: fee fie
! 2: huff and puff
! 3: mirror mirror
! 4: tick tock
!-88
! Choose fairly a tail
! 1: fee fie
! 2: huff and puff
! 3: mirror mirror
! 4: tick tock
!3.2
! Choose fairly a tail
! 1: fee fie
! 2: huff and puff
! 3: mirror mirror
! 4: tick tock
!2
! huff and puff
!$
 
module menu
public :: selector
contains
contains
function selector(title, options, n) result(choice)
integer, optional, intent(in) :: n
character(len=*), intent(in) :: title
character(len=*),dimension(:),intent(in) :: options
!character(len=:), allocatable :: choice ! requires deallocation
!allocate(character(len=8)::choice)
character(len=128) :: choice
integer :: i, L, ios
L = merge(n, size(options), present(n))
if (L .lt. 1) stop 'Silly input'
if (len(choice) .lt. len(options(1))) stop 'menu choices are excessively long'
i = 0
do while ((ios.ne.0) .or. ((i.lt.1) .or. (L.lt.i)))
write(6,*) title
write(6,"(i8,': ',a)")(i,options(i),i=1,L)
read(5,*,iostat=ios,end=666) i
end do
choice = options(i)
return
666 continue
stop 'Unexpected end of file'
end function selector
end module menu
 
function selector(title,options) result(choice)
program menu_demo
character(len=*),intent(in) :: title
use menu
character(len=14*), dimension(4:),intent(in) :: items = (/'fee fie ', 'huff and puff ', 'mirror mirror ','tick tock '/)options
character(len=len(options)) :: choice
print*,selector('Choose fairly a tail', items)
integer :: i,ichoose,ios,n
end program menu_demo
</lang>
 
choice = ""
=={{header|F Sharp|F#}}==
<lang fsharp>open System
 
n = size(options)
let rec menuChoice (options : string list) prompt =
if options(n => []0) then ""
else do
for i =print 0 to options.Length - 1 do"(a)",title
printfnprint "%d. %s(i8,"", "",a)",(i + 1) ,options.[(i]),i=1,n)
read (*,fmt="(i8)",iostat=ios) ichoose
 
if (ios == -1) exit ! EOF error
printf "%s" prompt
if (ios /= 0) cycle ! other error
let input = Int32.TryParse(Console.ReadLine())
if (ichoose < 1) cycle
if (ichoose > n) cycle ! out-of-bounds
 
match input withchoice = options(ichoose)
exit
| true, x when 1 <= x && x <= options.Length -> options.[x - 1]
end do
| _, _ -> menuChoice options prompt
end if
end function selector
end module menu
 
program menu_demo
[<EntryPoint>]
use menu
let main _ =
character(len=14),dimension(:),allocatable :: zero_items,fairytale
let menuOptions = ["fee fie"; "huff and puff"; "mirror mirror"; "tick tock"]
character(len=len(zero_items)) :: s
let choice = menuChoice menuOptions "Choose one: "
printfn "You chose: %s" choice
 
!! empty list demo
0</lang>
allocate(zero_items(0))
print "(a)","input items:",zero_items
s = selector('Choose from the empty list',zero_items)
print "(a)","returned:",s
if (s == "") print "(a)","(an empty string)"
 
!! Fairy tale demo
allocate(fairytale(4))
fairytale = (/'fee fie ','huff and puff ', &
'mirror mirror ','tick tock '/)
print "(a)","input items:",fairytale
s = selector('Choose a fairy tale',fairytale)
print "(a)","returned: ",s
if (s == "") print "(a)","(an empty string)"
 
end program menu_demo
 
</syntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">dim as string menu(1 to 4)={ "fee fie", "huff and puff", "mirror mirror", "tick tock" }
 
function menu_select( m() as string ) as string
dim as integer i, vc = 0
dim as string c
while vc<1 or vc > ubound(m)
cls
for i = 1 to ubound(m)
print i;" ";m(i)
next i
print
input "Choice? ", c
vc = val(c)
wend
return m(vc)
end function
 
print menu_select( menu() )</syntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
_window = 1
begin enum 1
_response
_popupBtn
end enum
 
void local fn BuildPopUpMenu
menu 101
menu 101, 0,, @"Select numbered menu item from the Three Pigs"
menu 101, 1,, @"1. fee fie"
menu 101, 2,, @"2. huff and puff"
menu 101, 3,, @"3. mirror mirror"
menu 101, 4,, @"4. tick tock"
menu 101, 5,, @" ?????????"
end fn
 
void local fn BuildWindow
CGRect r = fn CGRectMake( 0, 0, 480, 360 )
window _window, @"Rosetta Code Menu Task", r, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable + NSWindowStyleMaskMiniaturizable
r = fn CGRectMake( 45, 240, 380, 34 )
textlabel _response,, r, _window
ControlSetAlignment( _response, NSTextAlignmentCenter )
r = fn CGRectMake( 65, 200, 340, 34 )
popupbutton _popupBtn,,,, r, YES
PopUpButtonSetMenu( _popupBtn, 101 )
end fn
 
void local fn DoMenu( menuID as long, itemID as long )
select (menuID)
select (ItemID)
case 1 : ControlSetStringValue( _response, @"1. Sorry, wrong: From Jack the Giant Killer." )
case 2 : ControlSetStringValue( _response, @"2. CORRECT!: From The Three Little Pigs." )
case 3 : ControlSetStringValue( _response, @"3. Sorry, wrong: From Snow White and the Seven Dwarfs." )
case 4 : ControlSetStringValue( _response, @"4. Sorry, wrong: From Tick Tock Goes the Clock Rhyme." )
case 5 : ControlSetStringValue( _response, @"Surely you could just make a guess! Try again." )
end select
end select
end fn
 
fn BuildPopUpMenu
fn BuildWindow
 
on menu fn DoMenu
 
HandleEvents
</syntaxhighlight>
[[file:Rosetta_Code_FutureBasic_Menu_Task.png]]
 
 
=={{header|Gambas}}==
<syntaxhighlight lang="gambas">
Public Sub Main()
 
Dim asMenu As String[] = ["fee fie", "huff And puff", "mirror mirror", "tick tock"]
Dim sValuePrompt As String = "Please select one of the above numbers> "
Dim sChoice As String
Dim sFeedbackFormat As String = "You have chosen '&1'\r\n"
 
sChoice = Menu(asMenu, sValuePrompt)
If sChoice = "" Then
Print "menu returned an empty string"
Else
Print Subst(sFeedbackFormat, sChoice)
Endif
 
End
 
Private Function Menu(asChoices As String[], sPrompt As String) As String
 
Dim sReturnValue As String = ""
Dim sMenuLineFormat As String = "&1) &2"
Dim sAnswer As String
Dim iAnswer As Integer
Dim iIndex As Integer = 0
Dim sMenuItem As String
 
If Not IsNull(asChoices) Then
If asChoices.Count > 0 Then
Do
For iIndex = 0 To asChoices.Max
sMenuItem = asChoices[iIndex]
Print Subst(sMenuLineFormat, iIndex, sMenuItem)
Next
 
Print sPrompt
Input sAnswer
 
If IsNumber(sAnswer) Then
iAnswer = sAnswer
If (0 <= iAnswer) And (iAnswer <= asChoices.Max) Then
sReturnValue = asChoices[iAnswer]
Break
Endif
Endif
Loop
Endif
Endif
 
Return sReturnValue
 
End
</syntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 956 ⟶ 1,472:
pick = menu(choices, "Enter number: ")
fmt.Printf("You picked %q\n", pick)
}</langsyntaxhighlight>
Output:
<pre>
Line 968 ⟶ 1,484:
You picked "huff and puff"
</pre>
 
=={{header|GW-BASIC}}==
<syntaxhighlight lang="gwbasic">
10 DATA "Fee fie", "Huff and Puff", "Mirror mirror", "Tick tock"
20 VC = 0
30 DIM M$(3)
40 FOR I = 0 TO 3
50 READ M$(I)
60 NEXT I
70 CLS
80 FOR I = 0 TO 3
90 PRINT I+1;" ";M$(I)
100 NEXT I
110 PRINT
120 INPUT "Choice? ", C$
130 VC = VAL(C$)
140 IF VC<1 OR VC>4 THEN GOTO 70
150 PRINT "You picked ", M$(VC-1)
160 END
</syntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">module RosettaSelect where
 
import Data.Maybe (listToMaybe)
Line 993 ⟶ 1,529:
 
maybeRead :: Read a => String -> Maybe a
maybeRead = fmap fst . listToMaybe . filter (null . snd) . reads</langsyntaxhighlight>
 
Example usage, at the GHCI prompt:
<langsyntaxhighlight Haskelllang="haskell">*RosettaSelect> select ["fee fie", "huff and puff", "mirror mirror", "tick tock"]
1) fee fie
2) huff and puff
Line 1,003 ⟶ 1,539:
Choose an item: 3
"mirror mirror"
*RosettaSelect></langsyntaxhighlight>
 
=={{header|HicEst}}==
{{incorrect|HicEst|The function should return an empty string if called with an empty list. Please also check if this could really used as a [https://en.wikipedia.org/wiki/Subroutine function aka subroutine.]}}
<lang HicEst>CHARACTER list = "fee fie,huff and puff,mirror mirror,tick tock,", answer*20
<syntaxhighlight lang="hicest">CHARACTER list = "fee fie,huff and puff,mirror mirror,tick tock,", answer*20
 
POP(Menu=list, SelTxt=answer)
Line 1,014 ⟶ 1,551:
! The global variable $$ returns the selected list index
WRITE(Messagebox, Name) answer, $$
END</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
New version :
<lang Icon>procedure main()
Note the procedures below the "subroutines below" line are the actual
Rosetta task set.
 
procedure main() shows how to call the choose_from_menu "function", which demonstrates use of differing menu lists and a empty list.
 
<syntaxhighlight lang="icon">
## menu.icn : rewrite of the faulty version on Rosetta Code site 24/4/2021
 
procedure main()
L := ["fee fie", "huff and puff", "mirror mirror", "tick tock"]
K := ["hidie hi", "hidie ho", "mirror mirror on the Wall", "tick tock tick tok"]
Z := []
choice := choose_from_menu(L) # call using menu L
write("Returned value =", choice)
choice := choose_from_menu(K) # call using menu K
write("Returned value =", choice)
choice := choose_from_menu(Z) # call using empty list
write("Returned value =", choice)
 
every i := 1 to *L do
end ## of main
write(i,") ",L[i])
# --------- subroutines below ---------------------------------
 
procedure choose_from_menu(X)
displaymenu(X)
repeat {
writes("Choose a number from the menu above: ")
a := read()
if 1a <== integer"" then return(a) <= i then## no breakselection
write("You selected ",a)
if numeric(a) then {
if integer(a) <= 0 | integer(a) > *X then displaymenu(X) else
{ ## check entered option in range
write(a, " ==> ",X[a])
return ( string(a))
}
}
else displaymenu(X)
}
 
write("You selected ",a," ==> ",L[a])
end ## choose_from_menu(X)
end</lang>
 
procedure displaymenu(X)
every i := 1 to *X do
write(i,") ",X[i]) ## dispay menu options
end ## displaymenu(X)
 
</syntaxhighlight>
 
=={{header|J}}==
 
'''Solution:'''
<syntaxhighlight lang="j">
<lang j>require 'general/misc/prompt' NB. in older versions of J this was: require'misc'
CHOICES =: ];._2 'fee fie;huff and puff;mirror mirror;tick tock;'
showMenu =: i.@# smoutput@,&":&> ' '&,&.>
makeMsg PROMPT =: 'ChooseWhich ais numberfrom 0..'the ,three ':pigs? ',~ ":@<:@#
errorMsg =: [ smoutput bind 'Please choose a valid number!'
select=: ({::~ _&".@prompt@(makeMsg [ showMenu)) :: ($:@errorMsg)</lang>
See [[Talk:Select#J_implementation|Talk page]] for explanation of code.
 
showMenu =: smoutput@:(,"1~ (' ' ,.~ 3 ": i.@:(1 ,~ #)))
'''Example use:'''
read_stdin =: 1!:1@:1:
<lang j> select 'fee fie'; 'huff and puff'; 'mirror mirror'; 'tick tock'</lang>
 
menu =: '? '&$: :(4 : 0)
This would display:
NB. use: [prompt] menu choice_array
CHOICES =. y
if. 0 = # CHOICES do. return. end.
PROMPT =. x
whilst. RESULT -.@:e. i. # CHOICES do.
showMenu CHOICES
smoutput PROMPT
RESULT =. _1 ". read_stdin''
end.
RESULT {:: CHOICES
)
</syntaxhighlight>
 
See [[Talk:Select#J_implementation|Talk page]] for explanation.
0 fee fie
1 huff and puff
2 mirror mirror
3 tick tock
choose a number 0..3:
 
And, if the user responded with 2, would return: <tt>mirror mirror</tt>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java5">public static String select(List<String> list, String prompt){
if(list.size() == 0) return "";
Scanner sc = new Scanner(System.in);
Line 1,070 ⟶ 1,651:
}while(ret == null);
return ret;
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
{{works with|JScriptNode.js}} for the I/O.
<syntaxhighlight lang="javascript">const readline = require('readline');
<lang javascript>function select(question, choices) {
var prompt = "";
for (var i in choices)
prompt += i + ". " + choices[i] + "\n";
prompt += question;
 
async function menuSelect(question, choices) {
var input;
if (choices.length === 0) return '';
while (1) {
 
WScript.Echo(prompt);
const prompt = choices.reduce((promptPart, choice, i) => {
input = parseInt( WScript.StdIn.readLine() );
return promptPart += `${i + 1}. ${choice}\n`;
if (0 <= input && input < choices.length)
}, '');
break;
 
WScript.Echo("\nTry again.");
let inputChoice = -1;
}
while (inputChoice < 1 || inputChoice > choices.length) {
return input;
inputChoice = await getSelection(`\n${prompt}${question}: `);
}
 
return choices[inputChoice - 1];
}
 
function getSelection(prompt) {
return new Promise((resolve) => {
const lr = readline.createInterface({
input: process.stdin,
output: process.stdout
});
 
lr.question(prompt, (response) => {
lr.close();
resolve(parseInt(response) || -1);
});
});
}
 
varconst choices = ['fee fie', 'huff and puff', 'mirror mirror', 'tick tock'];
varconst choicequestion = select("'Which is from the three pigs?", choices)';
menuSelect(question, choices).then((answer) => {
WScript.Echo("you selected: " + choice + " -> " + choices[choice]);</lang>
console.log(`\nYou chose ${answer}`);
});</syntaxhighlight>
 
=={{header|jq}}==
{{works with|jq|1.5}}
This version uses jq 1.5's 'input' builtin to read programmatically from STDIN.
<langsyntaxhighlight lang="jq">def choice:
def read(prompt; max):
def __read__:
Line 1,116 ⟶ 1,713:
| if ($read|type) == "string" then $read
else "Thank you for selecting \($in[$read-1])" end
end ;</langsyntaxhighlight>
'''Example:'''
<langsyntaxhighlight lang="jq">["fee fie", "huff and puff", "mirror mirror", "tick tock"] | choice</langsyntaxhighlight>
<syntaxhighlight lang="sh">
<lang sh>
$ jq -n -r -f Menu.jq
Enter your choice:
Line 1,135 ⟶ 1,732:
 
1
Thank you for selecting fee fie</langsyntaxhighlight>
 
=={{header|Julia}}==
{{trans|Python}}
 
<syntaxhighlight lang="julia">using Printf
 
function _menu(items)
for (ind, item) in enumerate(items)
@printf " %2i) %s\n" ind item
end
end
 
_ok(::Any,::Any) = false
function _ok(reply::AbstractString, itemcount)
n = tryparse(Int, reply)
return isnull(n) || 0 ≤ get(n) ≤ itemcount
end
 
"Prompt to select an item from the items"
function _selector(items, prompt::AbstractString)
isempty(items) && return ""
reply = -1
itemcount = length(items)
while !_ok(reply, itemcount)
_menu(items)
print(prompt)
reply = strip(readline(STDIN))
end
return items[parse(Int, reply)]
end
 
items = ["fee fie", "huff and puff", "mirror mirror", "tick tock"]
item = _selector(items, "Which is from the three pigs: ")
println("You chose: ", item)</syntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
 
fun menu(list: List<String>): String {
if (list.isEmpty()) return ""
val n = list.size
while (true) {
println("\n M E N U\n")
for (i in 0 until n) println("${i + 1}: ${list[i]}")
print("\nEnter your choice 1 - $n : ")
val index = readLine()!!.toIntOrNull()
if (index == null || index !in 1..n) continue
return list[index - 1]
}
}
 
fun main(args: Array<String>) {
val list = listOf(
"fee fie",
"huff and puff",
"mirror mirror",
"tick tock"
)
val choice = menu(list)
println("\nYou chose : $choice")
}</syntaxhighlight>
Sample session:
{{out}}
<pre>
M E N U
 
1: fee fie
2: huff and puff
3: mirror mirror
4: tick tock
 
Enter your choice 1 - 4 : 0
 
M E N U
 
1: fee fie
2: huff and puff
3: mirror mirror
4: tick tock
 
Enter your choice 1 - 4 : asdf
 
M E N U
 
1: fee fie
2: huff and puff
3: mirror mirror
4: tick tock
 
Enter your choice 1 - 4 : 2
 
You chose : huff and puff
</pre>
 
=={{header|langur}}==
<syntaxhighlight lang="langur">val .select = impure fn(.entries) {
if .entries is not list: throw "invalid args"
if not .entries: return ""
 
# print the menu
writeln join "\n", map(fn .e, .i: "{{.i:2}}: {{.e}}", .entries, 1..len .entries)
 
val .idx = number read(
"Select entry #: ",
fn(.x) {
if not .x -> RE/^[0-9]+$/: return false
val .y = number .x
.y > 0 and .y <= len(.entries)
},
"invalid selection\n", -1,
)
 
.entries[.idx]
}
 
writeln .select(["fee fie", "eat pi", "huff and puff", "tick tock"])
</syntaxhighlight>
 
{{out}}
<pre> 1: fee fie
2: eat pi
3: huff and puff
4: tick tock
Select entry #: 7
invalid selection
Select entry #: 2
eat pi</pre>
 
=={{header|Logo}}==
{{incorrect|Logo|The function should return an empty string if called with an empty list. Please also check if this could really used as a [https://en.wikipedia.org/wiki/Subroutine function aka subroutine.]}}
{{works with|UCB Logo}}
<langsyntaxhighlight lang="logo">to select :prompt [:options]
foreach :options [(print # ?)]
forever [
Line 1,152 ⟶ 1,877:
[Which is from the three pigs?]
[fee fie] [huff and puff] [mirror mirror] [tick tock])
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function choiceselect (choiceslist)
if not list or #list == 0 then
for i, v in ipairs(choices) do print(i, v) end
return ""
end
local last, sel = #list
repeat
for i,option in ipairs(list) do
io.write(i, ". ", option, "\n")
end
io.write("Choose an item (1-", tostring(last), "): ")
sel = tonumber(string.match(io.read("*l"), "^%d+$"))
until type(sel) == "number" and sel >= 1 and sel <= last
return list[math.floor(sel)]
end
 
print("EnterNothing:", yourselect choice"{})
print()
local selection = io.read() + 0
print("You chose:", select {"fee fie", "huff and puff", "mirror mirror", "tick tock"})</syntaxhighlight>
 
{{out}}
if choices[selection] then print(choices[selection])
<pre>
else choice(choices)
Nothing:
end
end
 
1. fee fie
choice{"fee fie", "huff and puff", "mirror mirror", "tick tock"}</lang>
2. huff and puff
3. mirror mirror
4. tick tock
Choose an item (1-4): 0
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
Choose an item (1-4): a
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
Choose an item (1-4): 1.7
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
Choose an item (1-4): 10
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
Choose an item (1-4): 3
You chose: mirror mirror
</pre>
=={{header|M2000 Interpreter}}==
We use the dropdown menu, from M2000 Console. This menu open at text coordinates (moving to better position if can't fit to screen). We can choose something with enter + arrows or using mouse pointer. There is a way to feed the internal menu array, one by one, first using Menu without parameters, to clear the previous loaded menu, then using Menu + string expression, for each new item, and finally for opening the menu, we place: Menu !
 
The If$() statement return for boolean -1, 0 or for any number>0, as the Nth expression (from 1 to the last one).
=={{header|Mathematica}}==
 
<lang Mathematica>textMenu[data_List] := (MapIndexed[Print[#2[[1]], ") ", #] &, {a, b, c}];
<syntaxhighlight lang="m2000 interpreter">
While[! (IntegerQ[choice] && Length[data] > choice > 0),
Module TestMenu {
choice = Input["Enter selection"]];
Print "Make your choice: ";
data[[choice]])</lang>
Do
Use:
<pre>textMenu[{ Menu "fee fie", "huff and puff", "mirror mirror", "tick tock"}]</pre>
when menu=0
Print Menu$(Menu)
Print "That was the ";If$(Menu->"1st","2nd","3rd","4th");" option, bravo;"
}
TestMenu
</syntaxhighlight>
{{out}}
<pre>
Make your choice: mirror mirror
That was the 3rd option, bravo;
</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
'''Interpreter:''' Wolfram Desktop and Wolfram Desktop Kernel
{{works with|Wolfram Language|12}}
Redisplays the list of choices on every invalid input as per the task description. In the notebook interface (of Wolfram Desktop, at least), Print[] would most pragmatically be located outside of the loop because Input[] uses a dialog box.
 
<syntaxhighlight lang="mathematica">textMenu[data_List] := Module[{choice},
If[Length@data == 0, Return@""];
While[!(IntegerQ@choice && Length@data >= choice > 0),
MapIndexed[Print[#2[[1]], ") ", #1]&, data];
choice = Input["Enter selection..."]
];
data[[choice]]
]</syntaxhighlight>
{{out|Kernel (REPL) output|note=function definition omitted}}
<pre>Wolfram Desktop Kernel (using Wolfram Language 12.0.0) for Microsoft Windows (64-bit)
Copyright 1988-2019 Wolfram Research, Inc.
 
In[1]:= (*! ELIDED !*)
 
In[2]:= textMenu[{}]
 
Out[2]=
 
In[3]:= textMenu[{"fee fie", "huff and puff", "mirror mirror", "tick tock"}]
1) fee fie
2) huff and puff
3) mirror mirror
4) tick tock
Enter selection...0
1) fee fie
2) huff and puff
3) mirror mirror
4) tick tock
Enter selection...5
1) fee fie
2) huff and puff
3) mirror mirror
4) tick tock
Enter selection...-1
1) fee fie
2) huff and puff
3) mirror mirror
4) tick tock
Enter selection...fee fie
1) fee fie
2) huff and puff
3) mirror mirror
4) tick tock
Enter selection...3
 
Out[3]= mirror mirror</pre>
 
=={{header|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">function sucess = menu(list)
if numel(list) == 0
Line 1,215 ⟶ 2,042:
end
</syntaxhighlight>
</lang>
 
=={{header|min}}==
{{works with|min|0.19.3}}
min has an operator <code>choose</code> that nearly conforms to this task. The input list is altered so that the choice can be returned, and the empty list case is handled.
<syntaxhighlight lang="min">(
:prompt =list
(list bool)
(list (' dup append) map prompt choose)
("") if
) :menu
 
("fee fie" "huff and puff" "mirror mirror" "tick tock")
"Enter an option" menu
"You chose: " print! puts!</syntaxhighlight>
{{out}}
<pre>
Enter an option
1 - fee fie
2 - huff and puff
3 - mirror mirror
4 - tick tock
Enter your choice (1 - 4): 5
Invalid choice.
1 - fee fie
2 - huff and puff
3 - mirror mirror
4 - tick tock
Enter your choice (1 - 4): 1
You chose: fee fie
</pre>
 
=={{header|Modula-2}}==
{{incorrect|Modula-2|The function should return an empty string if called with an empty list. Please also check if this could really used as a [https://en.wikipedia.org/wiki/Subroutine function aka subroutine.]}}
<lang modula2>MODULE Menu;
<syntaxhighlight lang="modula2">MODULE Menu;
 
FROM InOut IMPORT WriteString, WriteCard, WriteLn, ReadCard;
Line 1,255 ⟶ 2,113:
WriteLn;
END (*of IF*)
END Menu.</langsyntaxhighlight>
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">MENU(STRINGS,SEP)
;http://rosettacode.org/wiki/Menu
NEW I,A,MAX
Line 1,272 ⟶ 2,130:
IF (A<1)!(A>MAX)!(A\1'=A) GOTO WRITEMENU
KILL I,MAX
QUIT $PIECE(STRINGS,SEP,A)</langsyntaxhighlight>
Usage:<pre>
USER>W !,$$MENU^ROSETTA("fee fie^huff and puff^mirror mirror^tick tock","^")
Line 1,312 ⟶ 2,170:
</pre>
 
=={{header|NimNanoquery}}==
{{trans|PythonUrsa}}
<syntaxhighlight lang="nanoquery">def _menu($items)
<lang nim>import strutils, rdstdin
for ($i = 0) ($i < len($items)) ($i = $i + 1)
println " " + $i + ") " + $items[$i]
end
end
 
def _ok($reply, $itemcount)
proc menu(xs) =
try
for i,x in xs: echo " ",i,") ",x
$n = int($reply)
return (($n >= 0) && ($n < $itemcount))
catch
return $false
end
end
 
def selector($items, $pmt)
proc ok(reply, count): bool =
// Prompt to select an item from the items
if (len($items) = 0)
return ""
end
$reply = -1
$itemcount = len($items)
while !_ok($reply, $itemcount)
_menu($items)
println $pmt
$reply = int(input())
end
return $items[$reply]
end
 
$items = list()
append $items "fee fie" "huff and puff" "mirror mirror" "tick tock"
$item = selector($items, "Which is from the three pigs: ")
println "You chose: " + $item</syntaxhighlight>
 
=={{header|Nim}}==
{{trans|Python}}
<syntaxhighlight lang="nim">import strutils, rdstdin
proc menu(xs: openArray[string]) =
for i, x in xs: echo " ", i, ") ", x
proc ok(reply: string; count: Positive): bool =
try:
let n = parseInt(reply)
return 0 <= n and n < count
except: return false
 
proc selector(xs,: openArray[string]; prompt: string): string =
if xs.len == 0: return ""
var reply = "-1"
Line 1,332 ⟶ 2,227:
reply = readLineFromStdin(prompt).strip()
return xs[parseInt(reply)]
 
const xs = ["fee fie", "huff and puff", "mirror mirror", "tick tock"]
let item = selector(xs, "Which is from the three pigs: ")
echo "You chose: ", item</langsyntaxhighlight>
 
Output:
{{out}}
<pre> 0) fee fie
1) huff and puff
Line 1,355 ⟶ 2,251:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">
let select ?(prompt="Choice? ") = function
| [] -> ""
Line 1,365 ⟶ 2,261:
with _ -> menu ()
in menu ()
</syntaxhighlight>
</lang>
 
Example use in the REPL:
<langsyntaxhighlight lang="ocaml">
# select ["fee fie"; "huff and puff"; "mirror mirror"; "tick tock"];;
0: fee fie
Line 1,376 ⟶ 2,272:
Choice? 2
- : string = "mirror mirror"
</syntaxhighlight>
</lang>
 
=={{header|OpenEdge/Progress}}==
<langsyntaxhighlight lang="progress">FUNCTION bashMenu RETURNS CHAR(
i_c AS CHAR
):
Line 1,428 ⟶ 2,324:
MESSAGE
bashMenu( "fee fie,huff and puff,mirror mirror,tick tock" )
VIEW-AS ALERT-BOX.</langsyntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
fun {Select Prompt Items}
case Items of nil then ""
Line 1,461 ⟶ 2,357:
in
{System.showInfo "You chose: "#Item}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
{{incorrect|PARI/GP|The function should return an empty string if called with an empty list. Please also check if this could really used as a [https://en.wikipedia.org/wiki/Subroutine function aka subroutine.]}}
<lang parigp>choose(v)=my(n);for(i=1,#v,print(i". "v[i]));while(type(n=input())!="t_INT"|n>#v|n<1,);v[n]
<syntaxhighlight lang="parigp">choose(v)=my(n);for(i=1,#v,print(i". "v[i]));while(type(n=input())!="t_INT"|n>#v|n<1,);v[n]
choose(["fee fie","huff and puff","mirror mirror","tick tock"])</lang>
choose(["fee fie","huff and puff","mirror mirror","tick tock"])</syntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free_Pascal}}
Tested with Free Pascal 2.6.4 (arm).
<langsyntaxhighlight lang="pascal">program Menu;
{$ASSERTIONS ON}
uses
Line 1,530 ⟶ 2,427:
 
dispose(MenuItems, Done);
end.</langsyntaxhighlight>
 
{{out}}
Line 1,554 ⟶ 2,451:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub menu
{
my ($prompt,@array) = @_;
Line 1,571 ⟶ 2,468:
$a = &menu($prompt,@a);
 
print "You chose: $a\n";</langsyntaxhighlight>
 
=={{header|Perl 6}}==
<lang perl6>sub menu ( $prompt, @items ) {
return '' unless @items.elems;
repeat until my $selection ~~ /^ \d+ $/ && @items[--$selection] {
my $i = 1;
say " {$i++}) $_" for @items;
$selection = prompt $prompt;
}
return @items[$selection];
}
 
my @choices = 'fee fie', 'huff and puff', 'mirror mirror', 'tick tock';
my $prompt = 'Enter the number corresponding to your selection: ';
 
my $answer = menu( $prompt, [] );
say "You chose: $answer" if $answer.chars;
 
$answer = menu( $prompt, @choices );
say "You chose: $answer" if $answer.chars;</lang>
 
=={{header|PL/I}}==
<lang PL/I>
test: proc options (main);
 
declare menu(4) character(100) varying static initial (
'fee fie', 'huff and puff', 'mirror mirror', 'tick tock');
declare (i, k) fixed binary;
 
do i = lbound(menu,1) to hbound(menu,1);
put skip edit (trim(i), ': ', menu(i) ) (a);
end;
put skip list ('please choose an item number');
get list (k);
if k >= lbound(menu,1) & k <= hbound(menu,1) then
put skip edit ('you chose ', menu(k)) (a);
else
put skip list ('Could not find your phrase');
 
end test;
</lang>
 
=={{header|Phix}}==
<syntaxhighlight lang="phix">function menu_select(sequence items, object prompt)
Slightly modified copy of [[Menu#Euphoria|Euphoria]]
sequence res = ""
<lang Phix>function menu_select(sequence items, object prompt)
items = remove_all("",items)
sequence res
if length(items)!=0 then
integer nres
if length(items)=0 then return 0while end1 ifdo
while for i=1 to length(items) do
for i = 1 to length printf(items1,"%d) do%s\n",{i,items[i]})
printf(1,"%d)end %s\n",{i,items[i]})for
puts(1,iff(atom(prompt)?"Choice?":prompt))
end for
res = scanf(trim(gets(0)),"%d")
 
puts(1,iff(atom(prompt)?"Choice?\n":prompt))
res = scanf if length(trim(gets(0)),"%d"res)=1 then
puts( integer nres = res[1,"\n")][1]
if nres>0 and nres<=length(resitems)=1 then
nres = res = items[1][1nres]
if nres>0 and nres<=length(items) then exit end if exit
end if
end whileif
return nres end while
end if
return res
end function
constant items = {"fee fie", "huff and puff", "mirror mirror", "tick tock"}
integerconstant nprompt = menu_select(items,"Which is from the three pigs? ")
string res = menu_select(items,prompt)
printf(1,"You chose %d(%s).\n",{n,items[n]})</lang>
printf(1,"You chose %s.\n",{res})</syntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$stdin = fopen("php://stdin", "r");
$allowed = array(1 => 'fee fie', 'huff and puff', 'mirror mirror', 'tick tock');
Line 1,655 ⟶ 2,514:
break;
}
}</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de choose (Prompt Items)
(use N
(loop
Line 1,664 ⟶ 2,523:
(prinl I ": " Item) )
(prin Prompt " ")
(flush)
(NIL (setq N (in NIL (read))))
(T (>= (length Items) N 1) (prinl (get Items N))) ) ) )
 
(choose "Which is from the three pigs?"
'("fee fie" "huff and puff" "mirror mirror" "tick tock") )</langsyntaxhighlight>
{{out}}
Output:
<pre>1: fee fie
1: fee fie
2: huff and puff
3: mirror mirror
4: tick tock
Which is from the three pigs? q
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"</pre>
</pre>
 
=={{header|PL/I}}==
{{incorrect|PL/I|The function should return an empty string if called with an empty list. Please also check if this could really used as a [https://en.wikipedia.org/wiki/Subroutine function aka subroutine.]}}
<syntaxhighlight lang="pl/i">
 
test: proc options (main);
 
declare menu(4) character(100) varying static initial (
'fee fie', 'huff and puff', 'mirror mirror', 'tick tock');
declare (i, k) fixed binary;
 
do i = lbound(menu,1) to hbound(menu,1);
put skip edit (trim(i), ': ', menu(i) ) (a);
end;
put skip list ('please choose an item number');
get list (k);
if k >= lbound(menu,1) & k <= hbound(menu,1) then
put skip edit ('you chose ', menu(k)) (a);
else
put skip list ('Could not find your phrase');
 
end test;
</syntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Select-TextItem
{
Line 1,724 ⟶ 2,617:
End
{
if(!$inputObject){
return ""
}
do
{
Line 1,737 ⟶ 2,633:
Write-Host ("{0,3}: {1}" -f 0,"To cancel")
 
[int]$choice = Read-Host $Prompt
 
$selectedValue = ""
Line 1,745 ⟶ 2,641:
$selectedValue = $menuOptions[$choice - 1]
}
 
}
until ($choice -match "^[0-9]+$" -and ($choice -eq 0 -or $choice -le $menuOptions.Count))
 
return $selectedValue
Line 1,753 ⟶ 2,650:
 
“fee fie”, “huff and puff”, “mirror mirror”, “tick tock” | Select-TextItem -Prompt "Select a string"
</syntaxhighlight>
</lang>
 
{{Out}}
Line 1,767 ⟶ 2,664:
 
=={{header|ProDOS}}==
{{incorrect|ProDOS|The function should return an empty string if called with an empty list. Please also check if this could really used as a [https://en.wikipedia.org/wiki/Subroutine function aka subroutine.]}}
<lang>
<syntaxhighlight lang="text">
:a
printline ==========MENU==========
Line 1,781 ⟶ 2,679:
printline You either chose an invalid choice or didn't chose.
editvar /newvar /value=goback /userinput=1 /title=Do you want to chose something else?
if -goback- /hasvalue y goto :a else exitcurrentprogram 1 </langsyntaxhighlight>
 
=={{header|Prolog}}==
{{works with|SWI-Prolog|6}}
<langsyntaxhighlight lang="prolog">
rosetta_menu([], "") :- !. %% Incase of an empty list.
rosetta_menu(Items, SelectedItem) :-
Line 1,803 ⟶ 2,701:
prompt1('Select a menu item by number:'),
read(Choice).
</syntaxhighlight>
</lang>
 
Example run:
 
<langsyntaxhighlight lang="prolog">
?- rosetta_menu(["fee fie", "huff and puff", "mirror mirror", "tick tock"], String).
 
Line 1,828 ⟶ 2,726:
Select a menu item by number:3.
String = "mirror mirror".
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
Define i, txt$, choice
Dim txts.s(4)
Line 1,857 ⟶ 2,755:
TheStrings:
Data.s "fee fie", "huff And puff", "mirror mirror", "tick tock"
EndDataSection</langsyntaxhighlight>
 
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">def _menu(items):
for indexitem in enumerate(items):
print (" %2i) %s" % indexitem)
Line 1,886 ⟶ 2,784:
items = ['fee fie', 'huff and puff', 'mirror mirror', 'tick tock']
item = selector(items, 'Which is from the three pigs: ')
print ("You chose: " + item)</langsyntaxhighlight>
 
Sample runs:
Line 1,915 ⟶ 2,813:
 
=={{header|R}}==
 
Uses [http://www.stat.ucl.ac.be/ISdidactique/Rhelp/library/base/html/menu.html menu].
<langsyntaxhighlight Rlang="r">showmenu <- function(choices = NULL)
{
if (is.null(choices)) return("")
choices <- c("fee fie", "huff and puff", "mirror mirror", "tick tock")
ans <- menu(choices)
if(ans==0) "" else choices[ans]
 
}
str <- showmenu(c("fee fie", "huff and puff", "mirror mirror", "tick tock"))</lang>
str <- showmenu()
</syntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 1,940 ⟶ 2,842:
 
(menu '("fee fie" "huff and puff" "mirror mirror" "tick tock"))
</syntaxhighlight>
</lang>
 
Sample Run:
Line 1,966 ⟶ 2,868:
"mirror mirror"
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub menu ( $prompt, @items ) {
return '' unless @items.elems;
repeat until my $selection ~~ /^ \d+ $/ && @items[--$selection] {
my $i = 1;
say " {$i++}) $_" for @items;
$selection = prompt $prompt;
}
return @items[$selection];
}
 
my @choices = 'fee fie', 'huff and puff', 'mirror mirror', 'tick tock';
my $prompt = 'Enter the number corresponding to your selection: ';
 
my $answer = menu( $prompt, [] );
say "You chose: $answer" if $answer.chars;
 
$answer = menu( $prompt, @choices );
say "You chose: $answer" if $answer.chars;</syntaxhighlight>
 
=={{header|REBOL}}==
{{incorrect|REBOL|The function should return an empty string if called with an empty list. Please also check if this could really used as a [https://en.wikipedia.org/wiki/Subroutine function aka subroutine.]}}
<syntaxhighlight lang="rebol">REBOL [
Title: "Text Menu"
URL: http://rosettacode.org/wiki/Select
]
 
choices: ["fee fie" "huff and puff" "mirror mirror" "tick tock"]
choice: ""
 
valid?: func [
choices [block! list! series!]
choice
][
if error? try [choice: to-integer choice] [return false]
all [0 < choice choice <= length? choices]
]
 
while [not valid? choices choice][
repeat i length? choices [print [" " i ":" choices/:i]]
choice: ask "Which is from the three pigs? "
]
print ["You chose:" pick choices to-integer choice]</syntaxhighlight>
 
Output:
 
<pre> 1 : fee fie
2 : huff and puff
3 : mirror mirror
4 : tick tock
Which is from the three pigs? klf
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
You chose: huff and puff</pre>
=={{header|Red}}==
<syntaxhighlight lang="red">Red ["text menu"]
 
menu: function [items][
print either empty? items [""] [until [
repeat n length? items [print [n ":" items/:n]]
attempt [pick items to-integer ask "Your choice: "]
]]
]</syntaxhighlight>
 
{{out}}
 
<pre>>> menu ["fee fie" "huff and puff" "mirror mirror" "tick tock"]
1 : fee fie
2 : huff and puff
3 : mirror mirror
4 : tick tock
Your choice: azerty
1 : fee fie
2 : huff and puff
3 : mirror mirror
4 : tick tock
Your choice: 7
1 : fee fie
2 : huff and puff
3 : mirror mirror
4 : tick tock
Your choice: 3
mirror mirror
>> menu []
 
>> </pre>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program displays a list, then prompts the user for a selection number (integer).*/
do forever /*keep prompting until response is OK. */
call list_create /*create the list from scratch. */
Line 2,004 ⟶ 3,002:
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
sayErr: say; say '***error***' arg(1) x; say; return</langsyntaxhighlight>
'''{{out|output''' |text=&nbsp; (which includes what the user entered):}}
<pre>
[item 1] fee fie
Line 2,017 ⟶ 3,015:
you chose item 2: huff and puff
</pre>
 
=={{header|REBOL}}==
<lang REBOL>REBOL [
Title: "Text Menu"
Author: oofoe
Date: 2009-12-08
URL: http://rosettacode.org/wiki/Select
]
 
choices: ["fee fie" "huff and puff" "mirror mirror" "tick tock"]
choice: ""
 
valid?: func [
choices [block! list! series!]
choice
][
if error? try [choice: to-integer choice] [return false]
all [0 < choice choice <= length? choices]
]
 
while [not valid? choices choice][
repeat i length? choices [print [" " i ":" choices/:i]]
choice: ask "Which is from the three pigs? "
]
print ["You chose:" pick choices to-integer choice]</lang>
 
Output:
 
<pre> 1 : fee fie
2 : huff and puff
3 : mirror mirror
4 : tick tock
Which is from the three pigs? klf
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
You chose: huff and puff</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aList = ["fee fie", "huff and puff", "mirror mirror", "tick tock"]
selected = menu(aList, "please make a selection: ")
Line 2,083 ⟶ 3,037:
end
return aList[index]
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,099 ⟶ 3,053:
mirror mirror
</pre>
 
=={{header|RPL}}==
≪ → prompt options
≪ '''IF''' options SIZE '''THEN'''
prompt options 1 CHOOSE
'''IF''' NOT '''THEN''' "" '''END'''
'''ELSE''' "" '''END'''
≫ '<span style="color:blue">SELECT</span>' STO
 
"Make a choice" { } <span style="color:blue">SELECT</span>
"Make a choice" { "fee fie" "huff and puff" "mirror mirror" "tick tock" } <span style="color:blue">SELECT</span>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">
<lang ruby>def select(prompt, items)
def select(prompt, items = [])
return "" if items.empty?
if items.empty?
loop do
''
items.each_index {|i| puts "#{i}. #{items[i]}"}
else
print "#{prompt}: "
beginanswer = -1
until (0...items.length).cover?(answer = Integer(gets)
items.each_with_index {|i,j| puts "#{j}. #{i}"}
rescue ArgumentError
redoprint "#{prompt}: "
begin
answer = Integer(gets)
rescue ArgumentError
redo
end
end
return items[answer] if (0...items.length).cover?(answer)
end
end
 
# test empty list
response = select("'Which is empty", []')
puts "empty list returns: >#{response}<\n"
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}<"</lang>
</syntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">dim choose$(5)
choose$(1) = "1 Fee Fie"
choose$(2) = "2 Huff Puff"
Line 2,156 ⟶ 3,126:
cls
end
end if</langsyntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
fn menu_select<'a>(items: &'a [&'a str]) -> &'a str {
if items.len() == 0 {
return "";
}
 
let stdin = std::io::stdin();
let mut buffer = String::new();
 
loop {
for (i, item) in items.iter().enumerate() {
println!("{}) {}", i + 1, item);
}
print!("Pick a number from 1 to {}: ", items.len());
 
// Read the user input:
stdin.read_line(&mut buffer).unwrap();
println!();
 
if let Ok(selected_index) = buffer.trim().parse::<usize>() {
if 0 < selected_index {
if let Some(selected_item) = items.get(selected_index - 1) {
return selected_item;
}
}
}
 
// The buffer will contain the old input, so we need to clear it before we can reuse it.
buffer.clear();
}
}
 
fn main() {
// Empty list:
let selection = menu_select(&[]);
println!("No choice: {:?}", selection);
 
// List with items:
let items = [
"fee fie",
"huff and puff",
"mirror mirror",
"tick tock",
];
 
let selection = menu_select(&items);
println!("You chose: {}", selection);
}
</syntaxhighlight>
 
=={{header|Scala}}==
===Scala idiom (Functional)===
<syntaxhighlight lang="text">import scala.util.Try
 
object Menu extends App {
val choice = menu(list)
 
def menu(menuList: Seq[String]): String = {
if (menuList.isEmpty) "" else {
val n = menuList.size
 
def getChoice: Try[Int] = {
println("\n M E N U\n")
menuList.zipWithIndex.map { case (text, index) => s"${index + 1}: $text" }.foreach(println(_))
print(s"\nEnter your choice 1 - $n : ")
Try {
io.StdIn.readInt()
}
}
 
menuList(Iterator.continually(getChoice)
.dropWhile(p => p.isFailure || !(1 to n).contains(p.get))
.next.get - 1)
}
}
 
def list = Seq("fee fie", "huff and puff", "mirror mirror", "tick tock")
 
println(s"\nYou chose : $choice")
}</syntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func string: menuSelect (in array string: items, in string: prompt) is func
Line 2,187 ⟶ 3,239:
begin
writeln("You chose " <& menuSelect(items, prompt));
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func menu (prompt, arr) {
arr.len > 0 || return ''
loop {
Line 2,206 ⟶ 3,258:
 
var answer = menu(prompt, list)
say "You choose: #{answer}"</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<syntaxhighlight lang="swift">func getMenuInput(selections: [String]) -> String {
guard !selections.isEmpty else {
return ""
}
 
func printMenu() {
for (i, str) in selections.enumerated() {
print("\(i + 1)) \(str)")
}
 
print("Selection: ", terminator: "")
}
 
while true {
printMenu()
 
guard let input = readLine(strippingNewline: true), !input.isEmpty else {
return ""
}
 
guard let n = Int(input), n > 0, n <= selections.count else {
continue
}
 
return selections[n - 1]
}
}
 
let selected = getMenuInput(selections: [
"fee fie",
"huff and puff",
"mirror mirror",
"tick tock"
])
 
print("You chose: \(selected)")</syntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc select {prompt choices} {
set nc [llength $choices]
if {!$nc} {
Line 2,228 ⟶ 3,319:
}
}
}</langsyntaxhighlight>
Testing it out interactively...
<langsyntaxhighlight lang="tcl">% puts >[select test {}]<
><
% puts >[select "Which is from the three pigs" {
Line 2,260 ⟶ 3,351:
4: tick tock
Which is from the three pigs: 2
>huff and puff<</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Line 2,291 ⟶ 3,382:
Output with <tt>FEE FIE:HUFF AND PUFF:MIRROR MIRROR:TICK TOCK</tt>
 
<syntaxhighlight lang="text"> 1:FEE FIE
2:HUFF AND PUFF
3:MIRROR MIRROR
4:TICK TOCK
? [flashing cursor]</langsyntaxhighlight>
 
 
Line 2,315 ⟶ 3,406:
Lbl D
Disp Str3
 
=={{header|True BASIC}}==
<syntaxhighlight lang="qbasic">DIM menu$(4)
MAT READ menu$
DATA "fee fie", "huff and puff", "mirror mirror", "tick tock"
 
FUNCTION sel$(choices$())
IF UBOUND(choices$) - LBOUND(choices$) = 0 THEN LET sel$ = ""
LET ret$ = ""
DO
FOR i = LBOUND(choices$) TO UBOUND(choices$)
PRINT i; ": "; choices$(i)
NEXT i
PRINT prompt$;
INPUT index
IF index <= UBOUND(choices$) AND index >= LBOUND(choices$) THEN LET ret$ = choices$(index)
LOOP WHILE ret$ = ""
LET sel$ = ret$
END FUNCTION
 
PRINT sel$(menu$())
END</syntaxhighlight>
 
=={{header|UNIX Shell}}==
 
This example uses the [http://www.softpanorama.org/Scripting/Shellorama/Control_structures/select_statements.shtml Bash select statement], but Bash did not invent this feature. The ''select'' loop comes originally from the [[Korn Shell]], and appears in some other shells. This loop always continues to read menu choices until the script breaks the loop, or the standard input reaches end of file (EOF).
 
Line 2,327 ⟶ 3,441:
{{works with|pdksh}}
{{works with|zsh}}
<langsyntaxhighlight lang="bash"># choose 'choice 1' 'choice 2' ...
# Prints menu to standard error. Prompts with PS3.
# Reads REPLY from standard input. Sets CHOICE.
Line 2,345 ⟶ 3,459:
choose 'fee fie' 'huff and puff' 'mirror mirror' 'tick tock'
[[ -n $CHOICE ]] && echo You chose: $CHOICE
[[ -z $CHOICE ]] && echo No input.</langsyntaxhighlight>
 
<pre>$ bash menu.sh
Line 2,364 ⟶ 3,478:
 
==={{header|es}}===
{{incorrect|es|The function should return an empty string if called with an empty list. Please also check if this could really used as a [https://en.wikipedia.org/wiki/Subroutine function aka subroutine.]}}
There is no ''select'' loop, but this ''es'' script provides just enough code to mimic one.
 
* ''Deviation from task:'' When the list of choices is empty, this function returns an empty list, not an empty string.
 
<langsyntaxhighlight lang="es"># choose 'choice 1' 'choice 2' ...
# Prints menu to standard error. Prompts with $prompt.
# Returns choice. If no input, returns empty list.
Line 2,421 ⟶ 3,536:
~ $#choice 1 && echo You chose: $choice
~ $#choice 0 && echo No input.
}</langsyntaxhighlight>
 
<pre>$ es menu.es
Line 2,433 ⟶ 3,548:
=={{header|Ursa}}==
{{trans|Python}}
<langsyntaxhighlight lang="ursa">def _menu (string<> items)
for (decl int i) (< i (size items)) (inc i)
out " " i ") " items<i> endl console
Line 2,469 ⟶ 3,584:
decl string item
set item (selector items "Which is from the three pigs: ")
out "You chose: " item endl console</langsyntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">'The Function
<lang vb>
Function Menu(ArrList, Prompt)
Do
Select Case False 'Non-standard usage hahaha
WScript.StdOut.Write "1. fee fie" & vbCrLf
Case IsArray(ArrList)
WScript.StdOut.Write "2. huff puff" & vbCrLf
Menu = "" 'Empty output string for non-arrays
WScript.StdOut.Write "3. mirror mirror" & vbCrLf
Exit Function
WScript.StdOut.Write "4. tick tock" & vbCrLf
Case UBound(ArrList) >= LBound(ArrList)
WScript.StdOut.Write "Please Enter Your Choice: " & vbCrLf
Menu = "" 'Empty output string for empty arrays
choice = WScript.StdIn.ReadLine
Exit Function
Select Case choice
End Select
Case "1"
'Display menu and prompt
WScript.StdOut.Write "fee fie" & vbCrLf
Do While True
Exit Do
For i = LBound(ArrList) To UBound(ArrList)
Case "2"
WScript.StdOut.WriteWriteLine((i + 1) & "huff. puff" & vbCrLfArrList(i))
Next
Exit Do
WScript.StdOut.Write(Prompt)
Case "3"
Choice = WScript.StdIn.ReadLine
WScript.StdOut.Write "mirror mirror" & vbCrLf
'Check if input is valid
Exit Do
If IsNumeric(Choice) Then 'Check for numeric-ness
Case "4"
If CStr(CLng(Choice)) = Choice Then 'Check for integer-ness (no decimal part)
WScript.StdOut.Write "tick tock" & vbCrLf
Index = Choice - 1 'Arrays are 0-based
Exit Do
'Check if Index is in array
Case Else
If LBound(ArrList) <= Index And Index <= UBound(ArrList) Then
WScript.StdOut.Write choice & " is an invalid choice. Please try again..." &_
Exit Do
vbCrLf & vbCrLf
End If
End Select
End If
Loop
End If
</lang>
WScript.StdOut.WriteLine("Invalid choice.")
Loop
Menu = ArrList(Index)
End Function
 
'The Main Thing
Sample = Array("fee fie", "huff and puff", "mirror mirror", "tick tock")
InputText = "Which is from the three pigs: "
WScript.StdOut.WriteLine("Output: " & Menu(Sample, InputText))</syntaxhighlight>
{{Out}}
<pre>C:\>cscript /nologo menu.vbs
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
Which is from the three pigs: cdsfklfm
Invalid choice.
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
Which is from the three pigs: -2
Invalid choice.
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
Which is from the three pigs: 3.14159
Invalid choice.
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
Which is from the three pigs: 45
Invalid choice.
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
Which is from the three pigs: 2
Output: huff and puff</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="Zig">
import os
 
const list = ["fee fie", "huff and puff", "mirror mirror", "tick tock"]
 
fn main() {
pick := menu(list, "Please make a selection: ")
if pick == -1 {
println("Error occured!\nPossibly list or prompt problem.")
exit(-1)
}
else {println("You picked: ${pick}. ${list[pick - 1]}")}
}
 
fn menu(list []string, prompt string) int {
mut index := -1
if list.len == 0 || prompt =='' {return -1}
println('Choices:')
for key, value in list {
println("${key + 1}: ${value}")
}
for index !in [1, 2, 3, 4] {index = os.input('${prompt}').int()}
return index
}
</syntaxhighlight>
 
{{out}}
<pre>
Choices:
1: fee fie
2: huff and puff
3: mirror mirror
4: tick tock
Please make a selection: 2
You picked: 2. huff and puff
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-ioutil}}
<syntaxhighlight lang="wren">import "./ioutil" for Input
 
var menu = Fn.new { |list|
var n = list.count
if (n == 0) return ""
var prompt = "\n M E N U\n\n"
for (i in 0...n) prompt = prompt + "%(i+1). %(list[i])\n"
prompt = prompt + "\nEnter your choice (1 - %(n)): "
var index = Input.integer(prompt, 1, n)
return list[index-1]
}
 
var list = ["fee fie", "huff and puff", "mirror mirror", "tick tock"]
var choice = menu.call(list)
System.print("\nYou chose : %(choice)")</syntaxhighlight>
 
{{out}}
Sample run:
<pre>
M E N U
 
F:\>cscript /nologo menu.vbs
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
 
Please Enter Your Choice:
Enter your choice (1 - 4): 6
9
9Must isbe an invalidinteger choice.between Please1 and 4, try again...
 
M E N U
 
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
 
Please Enter Your Choice:
Enter your choice (1 - 4): m
f
fMust isbe an invalidinteger choice.between Please1 and 4, try again...
 
M E N U
 
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
 
Please Enter Your Choice:
Enter your choice (1 - 4): 4
3
 
mirror mirror
You chose : tick tock
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">string 0;
<lang XPL0>include c:\cxpl\codes;
string 0;
 
func Menu(List);
Line 2,537 ⟶ 3,754:
int Size, I, C;
[Size:= List(0);
if Size < 1 then return List(0); \if empty list, return pointer to 0
for I:= 1 to Size-1 do
[IntOut(0, I); Text(0, ": ");
Line 2,552 ⟶ 3,769:
 
Text(0, Menu([5, "fee fie", "huff and puff", "mirror mirror", "tick tock",
"Which phrase is from the Three Little Pigs? "]))</langsyntaxhighlight>
 
Example output:
Line 2,565 ⟶ 3,782:
huff and puff
</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">// Rosetta Code problem: https://www.rosettacode.org/wiki/Menu
// by Jjuanhdez, 06/2022
 
dim choose$(5)
restore menudata
for a = 0 to 5 : read choose$(a) : next a
 
print menu$(choose$())
end
 
sub menu$(m$())
clear screen
repeat
print color("green","black") at(0,0) "Menu selection"
vc = 0
b = arraysize(m$(),1)
while vc < 1 or vc > b
for i = 1 to b-1
print i, " ", choose$(i)
next i
print choose$(b)
print
input "Your choice: " c
print at(0,7) "Your choice: "
if c > 0 and c < 6 then
vc = c
print color("yellow","black") at(0,8) choose$(vc)
else
print color("red","black") at(0,8) choose$(0)
break
fi
wend
until vc = 5
end sub
 
label menudata
data "Ack, not good", "fee fie ", "huff and puff"
data "mirror mirror", "tick tock ", "exit "</syntaxhighlight>
 
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn teleprompter(options){
os:=T("exit").extend(vm.arglist); N:=os.len();
if(N==1) return("");
Line 2,579 ⟶ 3,838:
 
teleprompter("fee fie" , "huff and puff" , "mirror mirror" , "tick tock")
.println();</langsyntaxhighlight>
{{out}}
<pre>
1,006

edits