Re: Add an element to the end of a list

On 04/03/2022 19:54, Martynas Jusevičius wrote:
> Okay, I think I figured it out -- UNION helps to handle the case of length=1:
> 
> PREFIX :    <http://example/>
> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
> 
> INSERT DATA {
>    :x0 :p () .
>    :x1 :p (1) .
>    :x2 :p (1 2) .
>    :x3 :p (1 2 3) .
> } ;
> 
> # The order here is important.
> # Must do list >= 1 first.
> 
> # List of length >= 1
> DELETE { ?elt rdf:rest rdf:nil }
> INSERT { ?elt rdf:rest [ rdf:first 98 ; rdf:rest rdf:nil ] }
> WHERE
> {
>    ?x :p ?list .
>    # List of length >= 1
>    {
>      ?list rdf:rest rdf:nil .
>      BIND (?list AS ?elt)
>    }
>    UNION
>    {
>      ?list rdf:rest+ ?elt .
>      ?elt rdf:rest rdf:nil .
>    }

Just need to change the + to a *

      ?list rdf:rest* ?elt .
      ?elt rdf:rest rdf:nil .

beause

      ?list rdf:rest* ?elt .

includes the effect of

      BIND (?list AS ?elt)

 Andy

>    # ?elt is last cons cell
> } ;
> 
> # List of length = 0
> DELETE { ?x :p rdf:nil . }
> INSERT { ?x :p [ rdf:first 99 ; rdf:rest rdf:nil ] }
> WHERE
> {
>     ?x :p rdf:nil .
> }
> 
> The result:
> 
> <http://example/x3>  <http://example/p>
>                  ( 1 2 3 98 ) .
> 
> <http://example/x2>  <http://example/p>
>                  ( 1 2 98 ) .
> 
> <http://example/x1>  <http://example/p>
>                  ( 1 98 ) .
> 
> <http://example/x0>  <http://example/p>
>                  ( 99 ) .
> 
> On Fri, Mar 4, 2022 at 7:56 PM Martynas Jusevičius
> <martynas@atomgraph.com> wrote:
>>
>> Hi,
>>
>> I need to create a property with an rdf:List value, if the property
>> doesn't exist, or append an item to the existing list.
>>
>> That seemed to exactly match the case "Add an element to the end of a
>> list" in Andy's document "Updating RDF Lists with SPARQL":
>> https://afs.github.io/rdf-lists-sparql#a-nameadd-lastaadd-an-element-to-the-end-of-a-list
>>
>> However, it didn't work in my case when the list length was equal to
>> 1. Then I tried running the SPARQL update from the document on an
>> empty Fuseki dataset and sure enough, it works for all cases except
>> when the list length is 1. Here's the resulting dataset:
>>
>> <http://example/x3>  <http://example/p>
>>                  ( 1 2 3 98 ) .
>>
>> <http://example/x2>  <http://example/p>
>>                  ( 1 2 98 ) .
>>
>> <http://example/x1>  <http://example/p>
>>                  ( 1 ) .
>>
>> <http://example/x0>  <http://example/p>
>>                  ( 99 ) .
>>
>> I think this is due to the property path pattern ?list rdf:rest+ ?elt
>> which does not match lists of length 1.
>>
>> Can someone confirm this and provide a complete version with a fix?
>> The document should probably be updated, too.
>>
>> Thanks.
>>
>> Martynas
>> atomgraph.com

Received on Sunday, 6 March 2022 11:16:36 UTC