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

58 lines
1.6 KiB
Perl
Raw Normal View History

2014-04-20 00:12:13 +04:00
package printer;
use strict;
use warnings FATAL => qw(all);
no if $] >= 5.018, warnings => "experimental::smartmatch";
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);
use Data::Dumper;
2014-04-20 00:12:13 +04:00
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->{val}}) . ')';
2014-04-20 00:12:13 +04:00
}
when(/^Vector/) {
return '[' . join(' ', map {_pr_str($_, $_r)} @{$obj->{val}}) . ']';
2014-04-20 00:12:13 +04:00
}
when(/^HashMap/) {
my @elems = ();
foreach my $key (keys $obj->{val}) {
push(@elems, _pr_str(String->new($key), $_r));
push(@elems, _pr_str($obj->{val}->{$key}, $_r));
2014-04-20 00:12:13 +04:00
}
return '{' . join(' ', @elems) . '}';
}
when(/^String/) {
if ($$obj =~ /^\x{029e}/) {
return ':' . substr($$obj,1);
} elsif ($_r) {
my $str = $$obj;
$str =~ s/\\/\\\\/g;
$str =~ s/"/\\"/g;
2014-04-22 05:48:16 +04:00
$str =~ s/\n/\\n/g;
return '"' . $str . '"';
} else {
return $$obj;
}
}
when(/^Function/) {
return '<fn* ' . _pr_str($obj->{params}) .
' ' . _pr_str($obj->{ast}) . '>';
}
when(/^Atom/) {
return '(atom ' . _pr_str($obj->{val}) . ")";
}
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;