Skip to content

Commit f53c920

Browse files
committed
add raw mode to repl
1 parent 8ac0d21 commit f53c920

File tree

2 files changed

+41
-8
lines changed

2 files changed

+41
-8
lines changed

README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,23 @@ You can switch to *bool-mode* by sending the `b` command:
8989
b> λx.λy.x
9090
true
9191

92+
Or `r` for raw mode:
93+
94+
$ php repl.php
95+
i> r
96+
r> λx.x
97+
array(4) {
98+
[0]=>
99+
string(2) "λ"
100+
[1]=>
101+
string(1) "x"
102+
[2]=>
103+
string(1) "x"
104+
[3]=>
105+
array(0) {
106+
}
107+
}
108+
92109
## Further reading
93110

94111
* [Lambda Calculus - Wikipedia](http://en.wikipedia.org/wiki/Lambda_calculus)

repl.php

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,27 @@
66

77
require 'vendor/autoload.php';
88

9-
function prompt($mode) {
9+
function prompt($mode)
10+
{
1011
echo "$mode> ";
1112

1213
return true;
1314
}
1415

15-
function format($result) {
16+
function format_raw($result)
17+
{
18+
ob_start();
19+
var_dump($result);
20+
return trim(ob_get_clean());
21+
}
22+
23+
function identity($x)
24+
{
25+
return $x;
26+
}
27+
28+
function format($result)
29+
{
1630
if (is_bool($result)) {
1731
return json_encode($result);
1832
}
@@ -25,19 +39,21 @@ function format($result) {
2539
while (prompt($mode) && false !== ($line = fgets(STDIN))) {
2640
$exp = trim($line);
2741

28-
if (in_array($exp, ['i', 'b'], true)) {
29-
$mode = $exp;
30-
continue;
31-
}
32-
3342
$factories = [
3443
'i' => 'igorw\lambda\to_int',
3544
'b' => 'igorw\lambda\to_bool',
45+
'r' => 'igorw\lambda\identity',
3646
];
3747

48+
if (in_array($exp, array_keys($factories), true)) {
49+
$mode = $exp;
50+
continue;
51+
}
52+
3853
try {
3954
$factory = $factories[$mode];
40-
echo format(evaluate($factory(parse($exp))))."\n";
55+
$format = __NAMESPACE__.'\\'.('r' === $mode ? 'format_raw' : 'format');
56+
echo $format(evaluate($factory(parse($exp))))."\n";
4157
} catch (\Exception $e) {
4258
echo $e->getMessage()."\n";
4359
}

0 commit comments

Comments
 (0)