I have found a good Prolog transpiler, which is released at here (https://gist.github.com/rla/3869174).
I have converted it from JavaScript to PHP. Below is my output code in PHP language:
<?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;
}
?>
Then, I have used a PHP Code Checker
to check about my output code. And, they alert that my code has some errors:
- Error: There is 1 line that is defining variables with too many equal signs '=': $ad == $bd;
- Parse error: syntax error, unexpected 'Var' (T_VAR), expecting identifier (T_STRING) or '(' in your code on line 5 function Var ()
Can you help me to fix it?