This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Animal::Discriminator { | |
| has @.animals; | |
| has $.question; | |
| method distinguish { | |
| my $discriminated := @!animals[yesno $.question ~ " "]; | |
| given $discriminated { | |
| when Str { | |
| if yesno "Is it a $_? " { | |
| True | |
| } else { | |
| my $new-animal = prompt "The animal you were thinking of was a? "; | |
| my $question = prompt "Please type a question that would distinguish a $new-animal from a $_\n? "; | |
| my $order = yesno "For a $new-animal the answer would be? "; | |
| $discriminated = Animal::Discriminator.new(:$question, :animals[($_, $new-animal)[!$order, $order]]); | |
| } | |
| } | |
| when Animal::Discriminator { | |
| .distinguish | |
| } | |
| default { | |
| say "Error: Expected Str or Animal::Discriminator, but found $_ instead."; | |
| } | |
| } | |
| } | |
| method list { @!animals.map(*.list) } | |
| } | |
| my $top = Animal::Discriminator.new( question => "Does it swim?", animals => <bird fish> ); | |
| while prompt "Are you thinking of an animal? " -> $_ { | |
| if m:i:s/^ [yes|y] / { | |
| $top.distinguish; | |
| say(); | |
| } | |
| else { | |
| say "I now know these animals:"; | |
| say " ", $_ for @$top; | |
| } | |
| } | |
| sub yesno ($prompt) { | |
| $_ = prompt $prompt; | |
| if m:i:s/^ [yes|y] / { True } | |
| elsif m:i:s/^ [no|n] / { False } | |
| else { | |
| note "I don't understand what “$_” means. Please say “yes” or “no”."; | |
| yesno $prompt; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment