弁財天

ゴフマン「専門家を信じるのではなく、自分自身で考えて判断せよ」

再帰的なパターンマッチ

[1,1]([1,2]([6,3],[6,4]),[1,2]([6,5],[6,6]),[1,2]([6,7],[6,8]),[1,2]([6,9],[6,10]),[1,2]([6,11],[6,12]),[1,2]([6,13],[6,14]),[1,2]([6,15],[6,16]),[1,2]([6,17],[6,18]))
のような文字列があってシステム全体で使われてる表記で、とても重要だとする。
[1,1]([1,2]([6,3],[5,2,"0"]))
[1,1]([6,2],[5,1,"00"],[5,1,"無"],[5,1,"有"])
なんかんじで、カギ括弧が丸括弧のリストで修飾されてるよーな文法だ。

Perl5.10から導入された再帰的パターンマッチで解析してみる。
Can I use Perl regular expressions to match balanced text?
これの応用w

#!/usr/bin/perl

use v5.10;
use strict;
#use warnings;

sub rec {
  my ($f, $nest, $op0) = @_;
  #print $f . "\n";
  $f =~ s/\(\)//;
  my @ma = $f =~ m/
    (\[\d+,\d+[^\(\)]*\])
    (
    \(
      (?:
        [^\(\)]++
        |
        (?1)
      )*
    \)
    )
    /xg;

  my $op =$1;
  #print "\$1 \"$op\"\n";
  if ($#ma > 0) {
	#print "#ma " . $#ma . "\n";
    for (my $loop = 0; $loop <= $#ma; $loop++) {
	  print $loop . " " . $ma[$loop] . "\n";
      &rec($ma[$loop], $nest+1, $op);
    }
  }
  else {
	if ($op0 ne $f) {
		print "x op \"$op0\"\n";
		print "x $f\n";
	}
	else {
		#print ".\n";
	}
  }
}

open(F, "Formula_ExpressionString.txt") or die("Can't open $! ...");
while() {
	chomp;
	my $line = $_;
	$line =~ s///;
	print "=== start..." . $line . "\n";
	&rec($line, 0, "");
	print "=== end.\n";
}
close(F);

=== start...[1,1]([1,2]([6,3],[6,4]),[1,2]([6,5],[6,6]),[1,2]([6,7],[6,8]),[1,2]([6,9],[6,10]),[1,2]([6,11],[6,12]),[1,2]([6,13],[6,14]),[1,2]([6,15],[6,16]),[1,2]([6,17],[6,18]))
0 [1,2]
1 ([6,3],[6,4])
x op "[1,2]"
x ([6,3],[6,4])
2 [1,2]
3 ([6,5],[6,6])
x op "[1,2]"
x ([6,5],[6,6])
4 [1,2]
5 ([6,7],[6,8])
x op "[1,2]"
x ([6,7],[6,8])
6 [1,2]
7 ([6,9],[6,10])
x op "[1,2]"
x ([6,9],[6,10])
8 [1,2]
9 ([6,11],[6,12])
x op "[1,2]"
x ([6,11],[6,12])
10 [1,2]
11 ([6,13],[6,14])
x op "[1,2]"
x ([6,13],[6,14])
12 [1,2]
13 ([6,15],[6,16])
x op "[1,2]"
x ([6,15],[6,16])
14 [1,2]
15 ([6,17],[6,18])
x op "[1,2]"
x ([6,17],[6,18])
=== end.
=== start...[1,1]([1,2]([6,3]),[5,2,&quot;0&quot;])
0 [1,2]
1 ([6,3])
x op "[1,2]"
x ([6,3])
=== end.
=== start...[1,1]([6,2],[5,1,&quot;00&quot;],[5,1,&quot;無&quot;],[5,1,&quot;有&quot;])
0 [1,1]
1 ([6,2],[5,1,&quot;00&quot;],[5,1,&quot;無&quot;],[5,1,&quot;有&quot;])
x op "[1,1]"
x ([6,2],[5,1,&quot;00&quot;],[5,1,&quot;無&quot;],[5,1,&quot;有&quot;])
=== end.

投稿されたコメント:

コメント
コメントは無効になっています。