#!/usr/bin/perl -w use strict; my %facts; # poor ( X ) :- # not rich( X ). my @owns = ( 2, merlyn => 'gold', ovid => 'pocket lint', ovid => 'cheap whiskey', kudra => 'domination fund' ); my @valuable = ( 1, 'gold', 'domination fund' ); my @thief = ( 1, 'badguy' ); $facts{ owns } = add_fact( \@owns ); $facts{ valuable } = add_fact( \@valuable ); $facts{ thief } = add_fact( \@thief ); foreach ( qw/ merlyn ovid kudra / ) { my $modifier = steals_from( 'badguy', $_ ) ? '' : ' not'; print "badguy will$modifier steal from $_\n"; } sub steals_from { # steals_from( X, Y ) :- # thief( X ), # rich( Y ). my ( $perp, $victim ) = @_; return thief( $perp ) && rich( $victim ); } sub thief { my $perp = shift; return grep { $_->[0] eq $perp } @{$facts{thief}}; } sub rich { # rich ( X ) :- # owns( X, Y ), # valuable( Y ). my $person = shift; my @results; my @items = map { $_->[1] } grep { $_->[0] eq $person } @{$facts{owns}}; foreach my $item ( @items ) { push @results => $item if grep { $_->[0] eq $item } @{$facts{valuable}}; } return @results ? 1 : 0; } sub add_fact { my $rule = shift; my $args = shift @$rule; my @rule; for ( my $i = 0; $i < @$rule; $i = $i + $args ) { my @args = @$rule[ $i .. $i + ( $args - 1 ) ]; push @rule => \@args; } return \@rule; }