Sum values in a recursion way ( n3 / n3logic )

Hi there,

I'm a newbie learning n3logic. For some interest, I'd like to sum a set of values, which are listed like this:

(:a :b :c) a rdf:List.
:a :hasValue 1.0.
:b :hasValue 2.0.
:c :hasValue 3.0.
:sum :hasValue 0.

I tried to sum them up in a recursive way:

# Recursion
{?L a rdf:List;
     rdf:first ?Z;
     rdf:rest ?R. 
   ?Z  :hasValue ?V.
   :sum :hasValue ?X.
   (?X ?V) math:sum ?Y. 
=> {?Z a :selected.
    ?R a rdf:List.    
   :sum :hasValue ?Y.

Recursion (final step)

{?L a rdf:List;
rdf:first ?Z;
rdf:rest rdf:nil.
?Z :hasValue ?V.
:sum :hasValue ?X.
(?X ?V) math:sum ?Y.
=> {?Z a :final;
a :selected.
:sum :hasFinalValue ?Y.

But it fails into a dead loop. I guess the problem occurs when updating :sum's value, but cannot find a way to make it work. Is there a way to compute this sum in n3, or is it just not suitable for n3 to do such thing? (Here is the full code: .n3 file)

Sorry if the problem is inappropriate here

If you have a SPARQL 1.1 processor, you can do the following:

SELECT sum(?elem)
{  ?list rdf:rest*/rdf:first ?elem
...where ?list is bound to the list node.

I think there have been warnings here and elsewhere not to get too tied up in N3 and/or n3logic. It's not a standard and its features aren't faring all that well in the RDF 2 working group. Standards compliance-speaking, it's best to stick with Turtle/SPARQL, at least in the short term.

The problem is quite appropriate here.

math:sum will compute the sum of all elements, you don't need to do something else then:

@prefix math: .

@forAll :x . { (1.0 2.0 3.0 4.0) math:sum :x . } => { [ :sum :x ] . } .

this except if you don't need to compute partial sums or want to experiment new ways, :)

edit: my apologise, i didn't notice that you have statements as elements of the list. You need first to extract the values into a separate list.