1 ! Copyright (c) 2012 Anonymous
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: formatting io kernel math math.parser sequences ;
6 ! http://rosettacode.org/wiki/Menu
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:
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.
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.
21 ! For test purposes use the four phrases: “fee fie”, “huff and
22 ! puff”, “mirror mirror” and “tick tock” in a list.
24 ! Note: This task is fashioned after the action of the Bash select statement.
26 : print-menu ( seq -- )
27 [ 1 + swap "%d - %s\n" printf ] each-index
28 "Your choice? " write flush ;
30 : select ( seq -- result )
32 readln string>number [
33 1 - swap 2dup bounds-check?
34 [ nth ] [ nip select ] if