kirouane/logic

dev-master 2019-06-18 11:42 UTC

This package is auto-updated.

Last update: 2024-09-18 23:53:09 UTC


README

这个 PHP 库受逻辑编程语言 PROLOG 的启发。熟悉 PROLOG 的人会发现一些有趣的功能。

安装

composer require kirouane/logic

示例

以下示例基于这篇关于 PROLOG 的优秀文章:尝试逻辑编程——PROLOG 的温和介绍

示例 1:查询

<?php
use Logic\Facts;
$likes = new Facts();

// fact declaration
$likes->is('alice', 'bob');
$likes->is('bob','carol');
$likes->is('james', 'mary');
$likes->is('mary', 'james');

/* Let's do some queries*/


var_dump($likes('alice', 'bob')->found());
//bool(true) | We found a match in our facts !

var_dump($likes('bob', 'alice')->found());
//bool(false) | Bob doesn't like alice according to our facts

var_dump($likes('mary', 'john')->found());
//bool(false) | Bob doesn't like alice according to our facts

示例 2:变量

现在,我们想知道 Alice 喜欢谁。我们通过使用变量来实现这一点。变量必须以下划线 _ 字符开始。让我们看一个例子。

/* Who does alice like? */
var_dump($likes('alice', '_Who')->toArray());

/*
array(1) {
  [0] =>
  array(1) {
    '_Who' =>
    string(3) "bob"
  }
}
*/

示例 3:规则

让我们使用上面定义的事实来写一个名为 "love compatible" 的规则。

$loveCompatible = new Rule(function($x, $y) use($likes) {
    /** @var RuleRunner $this */
    return $this->andLogic(
        $likes($x, $y),
        $likes($y, $x)
    );
});


/* Now let’s make some queries */

//Is james compatible with someone?
var_dump($loveCompatible('james', '_Who')->toArray());

/*
array(1) {
  [0] =>
  array(1) {
    '_Who' =>
    string(4) "mary"
  }
}
 */

// find all love pairs with the known facts
var_dump($loveCompatible('_X', '_Y')->toArray());

/*
array(2) {
  [0] =>
  array(2) {
    '_X' =>
    string(5) "james"
    '_Y' =>
    string(4) "mary"
  }
  [1] =>
  array(2) {
    '_X' =>
    string(4) "mary"
    '_Y' =>
    string(5) "james"
  }
}
 */

示例 4:规则

让我们看一个更复杂的例子。

$mother = new Facts();
$father = new Facts();

$mother->is('alice', 'lea');
$mother->is('john', 'julia');
$mother->is('lea', 'alberta');
$father->is('james', 'alfred');
$father->is('lea', 'john');


$parent = new Rule(function($x, $y) use($mother, $father) {
    return $this->orLogic(
        $mother($x, $y),
        $father($x, $y)
    );
});

$grandParent = new Rule(function($x, $y) use($parent) {
    $z = new Variable();

    return $this->andLogic(
        $parent($x, $z),
        $parent($z, $y)
    );
});


// Who are alice's grandparents
var_dump($grandParent('alice', '_Who')->toArray());

/*
array(2) {
  [0] =>
  array(1) {
    '_Who' =>
    string(7) "alberta"
  }
  [1] =>
  array(1) {
    '_Who' =>
    string(4) "john"
  }
}
*/

更多功能

  • 递归
  • 过滤
  • 能够使用原生 PHP 函数和运算符

即将推出的功能

  • 数组
  • 对象