]> gitweb.factorcode.org Git - factor.git/blob - extra/rosetta-code/menu/menu.factor
03d198e5f77f06600e05c40395a7a09fe2c8d6dd
[factor.git] / extra / rosetta-code / menu / menu.factor
1 ! Copyright (c) 2012 Anonymous
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: formatting io kernel math math.parser sequences ;
4 IN: rosetta-code.menu
5
6 ! http://rosettacode.org/wiki/Menu
7
8 ! Given a list containing a number of strings of which one is to
9 ! be selected and a prompt string, create a function that:
10
11 ! * Print a textual menu formatted as an index value followed by
12 !   its corresponding string for each item in the list.
13 ! * Prompt the user to enter a number.
14 ! * Return the string corresponding to the index number.
15
16 ! The function should reject input that is not an integer or is
17 ! an out of range integer index by recreating the whole menu
18 ! before asking again for a number. The function should return an
19 ! empty string if called with an empty list.
20
21 ! For test purposes use the four phrases: “fee fie”, “huff and
22 ! puff”, “mirror mirror” and “tick tock” in a list.
23
24 ! Note: This task is fashioned after the action of the Bash select statement.
25
26 : print-menu ( seq -- )
27     [ 1 + swap "%d - %s\n" printf ] each-index
28     "Your choice? " write flush ;
29
30 : select ( seq -- result )
31     dup print-menu
32     readln string>number [
33         1 - swap 2dup bounds-check?
34         [ nth ] [ nip select ] if
35     ] [ select ] if* ;