1
1
mirror of https://github.com/kanaka/mal.git synced 2024-11-13 11:23:59 +03:00
mal/perl/printer.pm

50 lines
1.4 KiB
Perl
Raw Normal View History

2014-04-20 00:12:13 +04:00
package printer;
use strict;
use warnings FATAL => qw(all);
use feature qw(switch);
2014-04-20 00:12:13 +04:00
use Exporter 'import';
our @EXPORT_OK = qw( _pr_str );
use types qw($nil $true $false);
sub _pr_str {
my($obj, $print_readably) = @_;
my($_r) = (defined $print_readably) ? $print_readably : 1;
2014-04-20 00:12:13 +04:00
given (ref $obj) {
when(/^List/) {
return '(' . join(' ', map {_pr_str($_, $_r)} @$obj) . ')';
2014-04-20 00:12:13 +04:00
}
when(/^Vector/) {
return '[' . join(' ', map {_pr_str($_, $_r)} @$obj) . ']';
2014-04-20 00:12:13 +04:00
}
when(/^HashMap/) {
my @elems = ();
foreach my $key (keys %$obj) {
push(@elems, _pr_str(String->new($key), $_r));
push(@elems, _pr_str($obj->{$key}, $_r));
2014-04-20 00:12:13 +04:00
}
return '{' . join(' ', @elems) . '}';
}
when(/^String/) {
if ($_r) {
my $str = $$obj;
$str =~ s/\\/\\\\/g;
$str =~ s/"/\\"/g;
$str =~ s/\n/\\n"/g;
return '"' . $str . '"';
} else {
return $$obj;
}
}
when(/^Function/) {
return '<fn* ' . _pr_str($obj->{params}) .
' ' . _pr_str($obj->{ast}) . '>';
}
2014-04-21 06:50:52 +04:00
when(/^CODE/) { return '<builtin_fn* ' . $obj . '>'; }
2014-04-20 00:12:13 +04:00
default { return $$obj; }
}
}
1;