Skip to content

Instantly share code, notes, and snippets.

@kasei
Last active April 16, 2019 16:19
Show Gist options
  • Save kasei/1b07b6299226901e142c0618786834f2 to your computer and use it in GitHub Desktop.
Save kasei/1b07b6299226901e142c0618786834f2 to your computer and use it in GitHub Desktop.
Accessing RDF lists using Attean
#!/usr/bin/env perl
use v5.18;
use Attean;
use Attean::RDF;
my $ns = URI::NamespaceMap->new( {
rdf => URI::Namespace->new('http://www.w3.org/1999/02/22-rdf-syntax-ns#'),
test => URI::Namespace->new('http://example.org/'),
});
my $ttl = <<'END';
@base <http://example.org/> .
@prefix test: <> .
<#test-list> a test:FixtureTable ;
test:fixtures ( <#test1> <#test2> ) .
END
my $p = Attean->get_parser('turtle')->new();
my $model = Attean->temporary_model();
my $iter = $p->parse_iter_from_bytes($ttl);
my $g = iri('http://example.org/g');
$model->add_iter($iter->as_quads($g));
say "Manually extracting list elements:";
manual_syntax($model);
say "\n";
say "Extracting list elements with `get_list`:";
shortcut_syntax($model);
sub manual_syntax {
my $model = shift;
my $tests_uri_iter = $model->objects(undef, iri($ns->test->fixtures->as_string))->materialize;
my ($list_head) = $tests_uri_iter->elements;
while (defined($list_head) and not $list_head->equals(iri($ns->rdf->nil->as_string))) {
my ($value) = $model->objects($list_head, iri($ns->rdf->first->as_string))->elements;
say "LIST ITEM: " . $value->as_string;
($list_head) = $model->objects($list_head, iri($ns->rdf->rest->as_string))->elements;
}
}
sub shortcut_syntax {
my $model = shift;
my $tests_uri_iter = $model->objects(undef, iri($ns->test->fixtures->as_string))->materialize;
my ($list_head) = $tests_uri_iter->elements;
my $iter = $model->get_list($g, $list_head);
foreach my $value ($iter->elements) {
say "LIST ITEM: " . $value->as_string;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment