Decision tables

sub decide (@q, @s) {
    my $bit = 2 ** [+] (1,2,4...*) Z* reverse @q.map: {
	so prompt(.value ~ "? ") ~~ /:i ^y/;
    }
    say "  $_" for @s.grep(*.key +& $bit)».value || "No clue!";
}

loop {
    decide
    (
	  "Y Y Y Y N N N N" => "Printer does not print",              
	  "Y Y N N Y Y N N" => "A red light is flashing",             
	  "Y N Y N Y N Y N" => "Printer is unrecognised",             
    ), 
    (
	:2<0_0_1_0_0_0_0_0> => "Check the power cable",                
	:2<1_0_1_0_0_0_0_0> => "Check the printer-computer cable",     
	:2<1_0_1_0_1_0_1_0> => "Ensure printer software is installed", 
	:2<1_1_0_0_1_1_0_0> => "Check/replace ink",                    
	:2<0_1_0_1_0_0_0_0> => "Check for paper jam",                  
    );
    say '';
}

A bit of explanation: we pass in two pair lists for the questions and solutions; we ignore the keys of the questions, since they can be generated by regarding them as a binary counter from right to left, with the least significant bit on the bottom. The @q.map runs the prompts and maps them to booleans using case-insensitive matching. We reverse that list and zip multiply with powers of two to figure out which bit we're going to grep for. (The zip stops on the shorter list, which is always going to be the list of booleans, since the list of powers of two is infinite.) We sum up those powers of two using a [+] reduction metaoperator, which in this case gives us a number from 0 to 7. Then we take 2 to that power.

The solutions list of pairs is conveniently keyed on binary numbers written in colon radix notation, so we grep the keys containing the correct bit, then map the pair list to its values using a hyperoperator to parallelize it. Unlike in Perl 5, we can use || on lists as well as scalars to provide a default result if nothing matches.

Printer does not print? n
A red light is flashing? y
Printer is unrecognised? n
  Check/replace ink

Printer does not print? y
A red light is flashing? n
Printer is unrecognised? y
  Check the power cable
  Check the printer-computer cable
  Ensure printer software is installed

Printer does not print? n
A red light is flashing? n
Printer is unrecognised? n
  No clue!

Printer does not print? ^C

Last updated