Skip to content

Instantly share code, notes, and snippets.

@choroba
Created July 9, 2016 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save choroba/2ed749cd881e10692ca189ff871ca5ea to your computer and use it in GitHub Desktop.
Save choroba/2ed749cd881e10692ca189ff871ca5ea to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use warnings;
use strict;
use Carp qw{ confess };
use List::Util qw{ shuffle };
use Test::More tests => 5;
use Benchmark qw{ cmpthese };
my @ATTRS;
my (
$ORD, $ROOT, $PARENT, $FIRSTCHILD, $NEXTSIBLING, $MISC, # both root and node
$FORM, $LEMMA, $UPOS, $XPOS, $FEATS, $DEPREL, $DEPS, # node only
);
BEGIN {
@ATTRS = qw(ord root parent firstchild nextsibling misc
form lemma upos xpos feats deprel deps);
($ORD, $ROOT, $PARENT, $FIRSTCHILD, $NEXTSIBLING, $MISC) = (0..5);
($FORM, $LEMMA, $UPOS, $XPOS, $FEATS, $DEPREL, $DEPS) = (6..12);
}
my $self = [ 0 .. 12 ];
sub ternary {
my @values = map {
$_ eq 'ord' ? $self->[$ORD]
: $_ eq 'form' ? $self->[$FORM]
: $_ eq 'lemma' ? $self->[$LEMMA]
: $_ eq 'upos' ? $self->[$UPOS]
: $_ eq 'xpos' ? $self->[$XPOS]
: $_ eq 'feats' ? $self->[$FEATS]
: $_ eq 'deprel' ? $self->[$DEPREL]
: $_ eq 'deps' ? $self->[$DEPS]
: $_ eq 'misc' ? $self->[$MISC]
: confess "Unknown attribute '$_'";
} @_;
}
{ my %h = ( ord => $ORD,
form => $FORM,
lemma => $LEMMA,
upos => $UPOS,
xpos => $XPOS,
feats => $FEATS,
deprel => $DEPREL,
deps => $DEPS,
misc => $MISC,
);
sub hash {
map $h{$_} // confess("Unknown attribute '$_'"), @_
}
}
my @values = shuffle qw( ord form lemma upos xpos feats deprel deps misc );
is_deeply [ ternary(@values) ], [ hash(@values) ], 'same values';
my $exception_regex = qr/^Unknown attribute 'x' at/;
isnt eval { ternary('x'); 1 }, 1, 'ternary dies';
like $@, $exception_regex, 'ternary exception';
isnt eval { hash('x'); 1 }, 1, 'hash dies';
like $@, $exception_regex, 'hash exception';
cmpthese( -5,
{ ternary => sub { ternary(@values) },
hash => sub { hash(@values) },
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment