我找到了一个很好的 Prolog transpiler ,这是在这里发布的(https://gist.github.com/rla/3869174)。
我已将其从 JavaScript 转换为 PHP 。以下是 PHP 语言的输出代码:
<?php
$util = require ('util');
function Var ()
{
$this->ref = $this;
}
function Struct()
{
$this->arguments = $arguments;
} =
function ()
{
$args = call_user_func(array(
Array ::prototype,
'slice'
) , 1);
return $this->arguments[0] + '(' + join(', ', $args->map($toString)) + ')';
};
$exports::Var = $Var;
$exports::Struct = $Struct;
function deref($term)
{
while (true)
{
if ($term instanceof $Var)
{
if ($term == $term->ref)
{
return $term;
}
else
{
$term = $term->ref;
}
}
else
{
return $term;
}
}
}
$exports->unify =
function ($a, $b, $stack, $cb)
{
if (unification($stack, $a, $b))
{
return $cb;
}
else
{
return backtrack($stack);
}
};
$exports->run =
function ($cb)
{
while ($cb = $cb())
{
}
};
function backtrack($stack)
{
$top = null;
while ($top = array_pop($stack) ())
{
if ($top instanceof $Var)
{
$top->ref = $top;
}
else
{
return $top;
}
}
}
function toString($term)
{
$term = deref($term);
if ($term instanceof $Var)
{
return '_';
}
else
{
return ();
}
}
function unification($stack, $a, $b)
{
$ad = deref($a);
$bd = deref($b);
$console->log(toString($ad) + ' ' + toString($bd));
if ($ad instanceof $Var)
{
$ad->ref = $bd;
array_push($stack, $ad);
}
else
if ($bd instanceof $Var)
{
$bd->ref = $ad;
array_push($stack, $bd);
}
else
if ($ad instanceof $Struct)
{
if ($bd instanceof $Struct)
{
if ($ad->arguments[0] == $bd->arguments[0] && count($ad->arguments) == count($bd->arguments))
{
for ($i = count($ad->arguments) - 1; $i >= 1; $i--)
{
if (!unification($stack, $ad->arguments[$i], $bd->arguments[$i]))
{
return false;
}
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return $ad == $bd;
}
return true;
}
?>
然后,我使用PHP Code Checker
检查输出代码。并且,他们警告我的代码有一些错误:
- 错误:有一行定义了具有太多等号的变量&#39; =&#39;: $ ad == $ bd;
- 解析错误:语法错误,意外&#39; Var&#39; (T_VAR),期待标识符(T_STRING)或&#39;(&#39;在第5行的代码中) 函数Var()
醇>
你能帮我解决一下吗?