Menu: Difference between revisions

16,945 bytes added ,  25 days ago
(Updated to work with Nim 1.4: added missing parameter types.)
(35 intermediate revisions by 18 users not shown)
Line 21:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">V items = [‘fee fie’, ‘huff and puff’, ‘mirror mirror’, ‘tick tock’]
 
L
Line 33:
I Int(reply) C 1..items.len
print(‘You chose: ’items[Int(reply) - 1])
L.break</langsyntaxhighlight>
 
{{out}}
Line 55:
</pre>
 
=={{header|Ada|Action!}}==
<syntaxhighlight lang="action!">DEFINE PTR="CARD"
<lang Ada>with ada.text_io,Ada.Strings.Unbounded; use ada.text_io, Ada.Strings.Unbounded;
 
BYTE FUNC Init(PTR ARRAY items)
items(0)="fee fie"
items(1)="huff and puff"
items(2)="mirror mirror"
items(3)="tick tock"
RETURN (4)
 
PROC ShowMenu(PTR ARRAY items BYTE count)
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)
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()
PTR ARRAY items(10)
BYTE count,res
 
count=Init(items)
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
Line 82 ⟶ 138:
put_line ("You chose " &
choice ((+"fee fie",+"huff and puff",+"mirror mirror",+"tick tock"),"Enter your choice "));
end menu;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 91 ⟶ 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 118 ⟶ 174:
 
printf(($"You chose "g"."l$, menu select(items, prompt)))
)</langsyntaxhighlight>
Output:
<pre>
Line 128 ⟶ 184:
You chose huff and puff.
</pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">menu: function [items][
selection: neg 1
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>
 
{{out}}
 
<pre>1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
Enter a number: something wrong
1. fee fie
2. huff and puff
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}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Menu(list:=""){
if !list ; if called with an empty list
return ; return an empty string
Line 139 ⟶ 228:
InputBox , Choice, Please Select From Menu, % string ,, % 200<len*7 ? 200 ? len*7 , % 120 + x.count()*20
return x[Choice]
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">list =
(
fee fie
Line 149 ⟶ 238:
MsgBox % Menu(list) ; call menu with list
MsgBox % Menu() ; call menu with empty list
return</langsyntaxhighlight>
 
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f MENU.AWK
BEGIN {
Line 178 ⟶ 267:
}
}
</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 197 ⟶ 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 212 ⟶ 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
<langsyntaxhighlight lang="dos">@echo off & setlocal enabledelayedexpansion
 
set "menuChoices="fee fie","huff and puff","mirror mirror","tick tock""
Line 246 ⟶ 412:
echo.Invalid Input. Please try again...
pause
goto :tryagain</langsyntaxhighlight>
Example 2
<langsyntaxhighlight lang="dos">
@echo off
 
Line 275 ⟶ 441:
echo.!string[%choice%]!
goto:eof
</syntaxhighlight>
</lang>
 
=={{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 298 ⟶ 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 322 ⟶ 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 368 ⟶ 534:
 
return items[choice - 1];
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">
using System;
using System.Collections.Generic;
Line 403 ⟶ 569:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <vector>
Line 455 ⟶ 621:
std::cout << "You chose: " << data_entry("> ", terms) << std::endl;
}
</syntaxhighlight>
</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 481 ⟶ 647:
}
 
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn menu [prompt choices]
(if (empty? choices)
""
Line 505 ⟶ 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 599 ⟶ 765:
.
 
END PROGRAM Prompt-Menu.</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun select (prompt choices)
(if (null choices)
""
Line 614 ⟶ 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 625 ⟶ 792:
try {
immutable n = input.to!int;
 
return typeof(return)((n >= 0 && n <= nEntries) ? n : -1);
} catch (Exception e) // Very generic
Line 638 ⟶ 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 650 ⟶ 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 659 ⟶ 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 682 ⟶ 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 701 ⟶ 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 720 ⟶ 990:
sel$=ret$
END PROCEDURE
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">include get.e
 
function menu_select(sequence items, object prompt)
Line 744 ⟶ 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#}}==
<langsyntaxhighlight lang="fsharp">open System
 
let rec menuChoice (options : string list) prompt =
Line 768 ⟶ 1,038:
printfn "You chose: %s" choice
 
0</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting io kernel math math.parser sequences ;
 
: print-menu ( seq -- )
Line 783 ⟶ 1,053:
] [ drop (select) ] if* ;
 
: select ( seq -- result ) [ "" ] [ (select) ] if-empty ;</langsyntaxhighlight>
 
Example usage:
Line 798 ⟶ 1,068:
=={{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.]}}
<langsyntaxhighlight lang="fantom">class Main
{
static Void displayList (Str[] items)
Line 833 ⟶ 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.
<langsyntaxhighlight Forthlang="forth">\ Rosetta Code Menu Idiomatic Forth
 
\ vector table compiler
Line 879 ⟶ 1,149:
CR [CHAR] 0 - SELECT
THEN
;</langsyntaxhighlight>
 
===If there must be lists===
Here we extend Forth to support simple lists and complete the task using the language extensions.
<langsyntaxhighlight lang="forth">\ Rosetta Menu task with Simple lists in Forth
 
: STRING, ( caddr len -- ) HERE OVER CHAR+ ALLOT PLACE ;
Line 946 ⟶ 1,216:
CR SWAP {NTH}
THEN
;</langsyntaxhighlight>
 
Test at the gForth console
Line 977 ⟶ 1,247:
 
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.
<syntaxhighlight lang="fortran">
<lang FORTRAN>
!a=./f && make $a && OMP_NUM_THREADS=2 $a
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
Line 1,035 ⟶ 1,305:
end program menu_demo
 
</syntaxhighlight>
</lang>
 
=={{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}}==
<langsyntaxhighlight lang="gambas">
Public Sub Main()
 
Line 1,089 ⟶ 1,433:
 
End
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,128 ⟶ 1,472:
pick = menu(choices, "Enter number: ")
fmt.Printf("You picked %q\n", pick)
}</langsyntaxhighlight>
Output:
<pre>
Line 1,140 ⟶ 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 1,165 ⟶ 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,175 ⟶ 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.]}}
<langsyntaxhighlight HicEstlang="hicest">CHARACTER list = "fee fie,huff and puff,mirror mirror,tick tock,", answer*20
 
POP(Menu=list, SelTxt=answer)
Line 1,187 ⟶ 1,551:
! The global variable $$ returns the selected list index
WRITE(Messagebox, Name) answer, $$
END</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
New version :
{{incorrect|Icon|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.]}}{{incorrect|Unicon|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].}}
Note the procedures below the "subroutines below" line are the actual
<lang Icon>procedure main()
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>
CHOICES =: ];._2 'fee fie;huff and puff;mirror mirror;tick tock;'
PROMPT =: 'Which is from the three pigs? '
Line 1,227 ⟶ 1,631:
RESULT {:: CHOICES
)
</syntaxhighlight>
</lang>
 
See [[Talk:Select#J_implementation|Talk page]] for explanation.
 
=={{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,247 ⟶ 1,651:
}while(ret == null);
return ret;
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
{{works with|Node.js}}
<langsyntaxhighlight lang="javascript">const readline = require('readline');
 
async function menuSelect(question, choices) {
Line 1,286 ⟶ 1,690:
menuSelect(question, choices).then((answer) => {
console.log(`\nYou chose ${answer}`);
});</langsyntaxhighlight>
 
=={{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,309 ⟶ 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,328 ⟶ 1,732:
 
1
Thank you for selecting fee fie</langsyntaxhighlight>
 
=={{header|Julia}}==
{{trans|Python}}
 
<langsyntaxhighlight lang="julia">using Printf
 
function _menu(items)
Line 1,362 ⟶ 1,766:
items = ["fee fie", "huff and puff", "mirror mirror", "tick tock"]
item = _selector(items, "Which is from the three pigs: ")
println("You chose: ", item)</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun menu(list: List<String>): String {
Line 1,389 ⟶ 1,793:
val choice = menu(list)
println("\nYou chose : $choice")
}</langsyntaxhighlight>
Sample session:
{{out}}
Line 1,424 ⟶ 1,828:
 
=={{header|langur}}==
<syntaxhighlight lang="langur">val .select = impure fn(.entries) {
{{works with|langur|0.7.1}}
if .entries is not list: throw "invalid args"
<lang langur>val .select = f(.entries) {
if not isArraylen(.entries) == 0: throwreturn "invalid args"
if len(.entries) == 0: return ZLS
 
# print the menu
writeln join "\n", map(ffn(.e, .i) $"\.i:2;: \.e;", .entries, 1..len .entries)
 
val .idx = toNumbernumber read(
"Select entry #: ",
ffn(.x) {
if not matching(.x -> RE/^[0-9]+$/, .x): return false
val .y = toNumbernumber .x
.y > 0 and .y <= len(.entries)
},
Line 1,445 ⟶ 1,848:
}
 
writeln .select(["fee fie", "eat pi", "huff and puff", "tick tock"])</langsyntaxhighlight>
 
{{out}}
Line 1,460 ⟶ 1,863:
{{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,473 ⟶ 1,876:
[Which is from the three pigs?]
[fee fie] [huff and puff] [mirror mirror] [tick tock])
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function select (list)
if not list or #list == 0 then
return ""
Line 1,493 ⟶ 1,896:
print("Nothing:", select {})
print()
print("You chose:", select {"fee fie", "huff and puff", "mirror mirror", "tick tock"})</langsyntaxhighlight>
 
{{out}}
Line 1,526 ⟶ 1,929:
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).
 
<syntaxhighlight lang="m2000 interpreter">
Module TestMenu {
Print "Make your choice: ";
Do
Menu "fee fie", "huff and puff", "mirror mirror", "tick tock"
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
Line 1,532 ⟶ 1,955:
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.
 
<langsyntaxhighlight Mathematicalang="mathematica">textMenu[data_List] := Module[{choice},
If[Length@data == 0, Return@""];
While[!(IntegerQ@choice && Length@data >= choice > 0),
Line 1,539 ⟶ 1,962:
];
data[[choice]]
]</langsyntaxhighlight>
{{out|Kernel (REPL) output|note=function definition omitted}}
<pre>Wolfram Desktop Kernel (using Wolfram Language 12.0.0) for Microsoft Windows (64-bit)
Line 1,580 ⟶ 2,003:
 
=={{header|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">function sucess = menu(list)
if numel(list) == 0
Line 1,618 ⟶ 2,041:
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.
<langsyntaxhighlight lang="min">(
:prompt =list
(list bool)
Line 1,632 ⟶ 2,055:
("fee fie" "huff and puff" "mirror mirror" "tick tock")
"Enter an option" menu
"You chose: " print! puts!</langsyntaxhighlight>
{{out}}
<pre>
Line 1,652 ⟶ 2,075:
=={{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.]}}
<langsyntaxhighlight lang="modula2">MODULE Menu;
 
FROM InOut IMPORT WriteString, WriteCard, WriteLn, ReadCard;
Line 1,689 ⟶ 2,112:
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,706 ⟶ 2,129:
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,748 ⟶ 2,171:
=={{header|Nanoquery}}==
{{trans|Ursa}}
<langsyntaxhighlight Nanoquerylang="nanoquery">def _menu($items)
for ($i = 0) ($i < len($items)) ($i = $i + 1)
println " " + $i + ") " + $items[$i]
Line 1,781 ⟶ 2,204:
append $items "fee fie" "huff and puff" "mirror mirror" "tick tock"
$item = selector($items, "Which is from the three pigs: ")
println "You chose: " + $item</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import strutils, rdstdin
proc menu(xs: openArray[string]) =
Line 1,806 ⟶ 2,229:
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>
 
{{out}}
Line 1,827 ⟶ 2,250:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">
let select ?(prompt="Choice? ") = function
| [] -> ""
Line 1,837 ⟶ 2,260:
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,848 ⟶ 2,271:
Choice? 2
- : string = "mirror mirror"
</syntaxhighlight>
</lang>
 
=={{header|OpenEdge/Progress}}==
<langsyntaxhighlight lang="progress">FUNCTION bashMenu RETURNS CHAR(
i_c AS CHAR
):
Line 1,900 ⟶ 2,323:
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,933 ⟶ 2,356:
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.]}}
<langsyntaxhighlight 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"])</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free_Pascal}}
Tested with Free Pascal 2.6.4 (arm).
<langsyntaxhighlight lang="pascal">program Menu;
{$ASSERTIONS ON}
uses
Line 2,003 ⟶ 2,426:
 
dispose(MenuItems, Done);
end.</langsyntaxhighlight>
 
{{out}}
Line 2,027 ⟶ 2,450:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub menu
{
my ($prompt,@array) = @_;
Line 2,044 ⟶ 2,467:
$a = &menu($prompt,@a);
 
print "You chose: $a\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
<langsyntaxhighlight Phixlang="phix">function menu_select(sequence items, object prompt)
sequence res = ""
items = remove_all("",items)
Line 2,073 ⟶ 2,496:
constant prompt = "Which is from the three pigs? "
string res = menu_select(items,prompt)
printf(1,"You chose %s.\n",{res})</langsyntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$stdin = fopen("php://stdin", "r");
$allowed = array(1 => 'fee fie', 'huff and puff', 'mirror mirror', 'tick tock');
Line 2,090 ⟶ 2,513:
break;
}
}</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de choose (Prompt Items)
(use N
(loop
Line 2,103 ⟶ 2,526:
(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}}
<pre>
Line 2,126 ⟶ 2,549:
=={{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">
<lang PL/I>
 
test: proc options (main);
Line 2,145 ⟶ 2,568:
 
end test;
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Select-TextItem
{
Line 2,226 ⟶ 2,649:
 
“fee fie”, “huff and puff”, “mirror mirror”, “tick tock” | Select-TextItem -Prompt "Select a string"
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,241 ⟶ 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.]}}
<syntaxhighlight lang="text">
:a
printline ==========MENU==========
Line 2,255 ⟶ 2,678:
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 2,277 ⟶ 2,700:
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 2,302 ⟶ 2,725:
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 2,331 ⟶ 2,754:
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 2,360 ⟶ 2,783:
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 2,391 ⟶ 2,814:
 
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("")
Line 2,400 ⟶ 2,823:
str <- showmenu(c("fee fie", "huff and puff", "mirror mirror", "tick tock"))
str <- showmenu()
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 2,418 ⟶ 2,841:
 
(menu '("fee fie" "huff and puff" "mirror mirror" "tick tock"))
</syntaxhighlight>
</lang>
 
Sample Run:
Line 2,447 ⟶ 2,870:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub menu ( $prompt, @items ) {
return '' unless @items.elems;
repeat until my $selection ~~ /^ \d+ $/ && @items[--$selection] {
Line 2,464 ⟶ 2,887:
 
$answer = menu( $prompt, @choices );
say "You chose: $answer" if $answer.chars;</langsyntaxhighlight>
 
=={{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.]}}
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Text Menu"
URL: http://rosettacode.org/wiki/Select
Line 2,488 ⟶ 2,911:
choice: ask "Which is from the three pigs? "
]
print ["You chose:" pick choices to-integer choice]</langsyntaxhighlight>
 
Output:
Line 2,509 ⟶ 2,932:
You chose: huff and puff</pre>
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">Red ["text menu"]
 
menu: function [items][
Line 2,516 ⟶ 2,939:
attempt [pick items to-integer ask "Your choice: "]
]]
]</langsyntaxhighlight>
 
{{out}}
Line 2,542 ⟶ 2,965:
 
=={{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,578 ⟶ 3,001:
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
sayErr: say; say '***error***' arg(1) x; say; return</langsyntaxhighlight>
{{out|output|text=&nbsp; (which includes what the user entered):}}
<pre>
Line 2,593 ⟶ 3,016:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aList = ["fee fie", "huff and puff", "mirror mirror", "tick tock"]
selected = menu(aList, "please make a selection: ")
Line 2,613 ⟶ 3,036:
end
return aList[index]
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,629 ⟶ 3,052:
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}}==
<langsyntaxhighlight lang="ruby">
def select(prompt, items = [])
if items.empty?
Line 2,658 ⟶ 3,092:
response = select('Which is from the three pigs', items)
puts "you chose: >#{response}<"
</syntaxhighlight>
</lang>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">dim choose$(5)
choose$(1) = "1 Fee Fie"
choose$(2) = "2 Huff Puff"
Line 2,691 ⟶ 3,125:
cls
end
end if</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
fn menu_select<'a>(items: &'a [&'a str]) -> &'a str {
if items.len() == 0 {
Line 2,742 ⟶ 3,176:
println!("You chose: {}", selection);
}
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
===Scala idiom (Functional)===
<syntaxhighlight lang="text">import scala.util.Try
 
object Menu extends App {
Line 2,773 ⟶ 3,207:
 
println(s"\nYou chose : $choice")
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func string: menuSelect (in array string: items, in string: prompt) is func
Line 2,804 ⟶ 3,238:
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,823 ⟶ 3,257:
 
var answer = menu(prompt, list)
say "You choose: #{answer}"</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">func getMenuInput(selections: [String]) -> String {
guard !selections.isEmpty else {
return ""
Line 2,862 ⟶ 3,296:
])
 
print("You chose: \(selected)")</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc select {prompt choices} {
set nc [llength $choices]
if {!$nc} {
Line 2,884 ⟶ 3,318:
}
}
}</langsyntaxhighlight>
Testing it out interactively...
<langsyntaxhighlight lang="tcl">% puts >[select test {}]<
><
% puts >[select "Which is from the three pigs" {
Line 2,916 ⟶ 3,350:
4: tick tock
Which is from the three pigs: 2
>huff and puff<</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Line 2,947 ⟶ 3,381:
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,971 ⟶ 3,405:
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}}==
Line 2,984 ⟶ 3,440:
{{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 3,002 ⟶ 3,458:
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 3,026 ⟶ 3,482:
* ''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 3,079 ⟶ 3,535:
~ $#choice 1 && echo You chose: $choice
~ $#choice 0 && echo No input.
}</langsyntaxhighlight>
 
<pre>$ es menu.es
Line 3,091 ⟶ 3,547:
=={{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 3,127 ⟶ 3,583:
decl string item
set item (selector items "Which is from the three pigs: ")
out "You chose: " item endl console</langsyntaxhighlight>
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">'The Function
Function Menu(ArrList, Prompt)
Select Case False 'Non-standard usage hahaha
Line 3,165 ⟶ 3,621:
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))</langsyntaxhighlight>
{{Out}}
<pre>C:\>cscript /nologo menu.vbs
Line 3,198 ⟶ 3,654:
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
 
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
 
Enter your choice (1 - 4): 6
Must be an integer between 1 and 4, try again.
 
M E N U
 
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
 
Enter your choice (1 - 4): m
Must be an integer between 1 and 4, try again.
 
M E N U
 
1. fee fie
2. huff and puff
3. mirror mirror
4. tick tock
 
Enter your choice (1 - 4): 4
 
You chose : tick tock
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">string 0;
 
func Menu(List);
Line 3,221 ⟶ 3,768:
 
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 3,234 ⟶ 3,781:
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 3,248 ⟶ 3,837:
 
teleprompter("fee fie" , "huff and puff" , "mirror mirror" , "tick tock")
.println();</langsyntaxhighlight>
{{out}}
<pre>
880

edits