Task

Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:

 prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
 prompts the user to enter a number;
 returns the string corresponding to the selected index number.


The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.

For test purposes use the following four phrases in a list:

   fee fie
   huff and puff
   mirror mirror
   tick tock

Note

This task is fashioned after the action of the Bash select statement.

def _menu($items)
	for ($i = 0) ($i < len($items)) ($i = $i + 1)
		println "  " + $i + ") " + $items[$i]
	end
end
 
def _ok($reply, $itemcount)
	try
		$n = int($reply)
		return (($n >= 0) && ($n < $itemcount))
	catch
		return $false
	end
end
 
def selector($items, $pmt)
	// 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