2

I'm looking for effective implementation of Material Implication/XNp/If/then for PHP. Here's example of where I want to use it:

There is collection of object. Each of them has date and type.

I'm writing method that accepts three parameters:

function isNewest($obj, $collection, $sameTypeOnly = true){}

and check if the $obj has newer date (bigger timestamp) than any of objects in $collection. I also want to depend my comparison on $sameTypeOnly which narrows comparations only to objects of same type.

So far I have:

$currentDate = strtotime($obj->getDate());

foreach($relatedObjects as $related){
   if($currentDate < strtotime($related->getDate()) && >>SOMETHING<<){
       return false;
   }
}

return true;

There is problem with SOMETHING. I want it to check if $sameTypeOnly is true, and if it is, check if $obj->getType() == $related->getType().

Of course, I could do that using nested if() statements like this: $currentDate = strtotime($obj->getDate());

foreach($relatedObjects as $related){
   if($sameTypeOnly){
       if($obj->getType() == $related->getType() && $currentDate < strtotime($related->getDate()){
           return false;
       }
   } else {
       if($currentDate < strtotime($related->getDate()){
           return false;
       }
   }
}

return true;

and it will work! BUT IT LOOKS BAD. I wonder if there is simplier, effective and elegant solution to do this in one if.

After minute of thinking I got my truth table. Assuming that T stands for same type, t1 = t2 means that type of first objects matches type of second objects, and r is result, truth table looks like this:

 T | t1 = t2 | r
---|---------|----
 T |    T    | T
---|---------|----
 T |    F    | F
---|---------|----
 F |    T    | T
---|---------|----
 F |    F    | T

I looked up for similar table here, and well, here it is! Column 11 on this table (named "if/then"). I googled for PHP implementation of this operation, with no luck.

Is there any way to implement it using only operators available in PHP? Will it be efficient and fast?

4

1 回答 1

1

是的,有一种方法,我想它会很快,因为这是非常简单的操作。

function implication($p, $q) {
    return !$p | $q;
}

您可能想出于自己的目的|进行交换。||

让我们为此生成真值表:

$values = array(0,1);

echo "p q r\n";

foreach ($values as $p) {
    foreach($values as $q) {
        echo "$p $q " . implication($p, $q) . "\n";
    }
}

输出:

p q r
0 0 1
0 1 1
1 0 0
1 1 1

这相当于您提供的真值表。

于 2014-05-22T11:19:07.723 回答