Skip to content

Commit baf681a

Browse files
committed
add binary lambda calculus parsing
1 parent 8fba985 commit baf681a

File tree

3 files changed

+74
-2
lines changed

3 files changed

+74
-2
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,6 @@
1313
"jakubledl/dissect": "dev-develop"
1414
},
1515
"autoload": {
16-
"files": ["src/eval.php", "src/parser.php", "src/krivine.php"]
16+
"files": ["src/eval.php", "src/parser.php", "src/krivine.php", "src/binary.php"]
1717
}
1818
}

composer.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/binary.php

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
<?php
2+
3+
namespace igorw\lambda\binary;
4+
5+
// parse, return pair of [parsed, offset]
6+
// parsed uses de-bruijn indices
7+
function parse_term($bits)
8+
{
9+
if ('00' === substr($bits, 0, 2)) {
10+
list($body, $rest) = parse_term(substr($bits, 2));
11+
12+
return [
13+
['λ', $body],
14+
$rest,
15+
];
16+
}
17+
18+
if ('01' === substr($bits, 0, 2)) {
19+
$rest = substr($bits, 2);
20+
list($l, $rest) = parse_term($rest);
21+
list($r, $rest) = parse_term($rest);
22+
23+
return [
24+
[$l, $r],
25+
$rest,
26+
];
27+
}
28+
29+
if ('1' === $bits[0]) {
30+
$i = 0;
31+
while ($bits[++$i] !== '0');
32+
33+
return [
34+
['offset', $i],
35+
substr($bits, $i + 1),
36+
];
37+
}
38+
39+
throw new \InvalidArgumentException("Invalid binary term '$bits'");
40+
}
41+
42+
function parse($bits)
43+
{
44+
$bits = preg_replace('/\s/s', '', $bits);
45+
list($parsed, $rest) = parse_term($bits);
46+
47+
if (strlen($rest) > 0) {
48+
throw new \InvalidArgumentException("Non-closed binary term '$bits' had remaining part '$rest'");
49+
}
50+
51+
return $parsed;
52+
}
53+
54+
// identity
55+
// ['λ', ['offset', 1]]
56+
// var_dump(parse('0010'));
57+
58+
// false
59+
// ['λ', ['λ', ['offset', 1]]]
60+
// var_dump(parse('000010'));
61+
62+
// true
63+
// ['λ', ['λ', ['offset', 2]]]
64+
// var_dump(parse('0000110'));
65+
66+
// λx.x x
67+
// ['λ', [['offset', 1], ['offset', 1]]]
68+
// var_dump(parse('00 01 10 10'));
69+
70+
// λx.false
71+
// ['λ', ['λ', ['λ', ['offset', 1]]]]
72+
// var_dump(parse('00000010'));

0 commit comments

Comments
 (0)