Reputation: 13
I have predicates as follows
dur(a,1).
dur(b,2).
dur(c,3).
dur(d,4).
Say I want to add the elements of a list [a,b,c] so sum = 6. How do I access the value associated with the variable?
Because something like this
len([],0).
len([H|T], Sum) :-
len(T, Rest),
Sum is H + Rest.
doesn't work, it works fine for [1,2,3] but not at all for [a,b,c] which makes sense, but I don't have a clue how to make it work for list len([a,b,c],Sum).
Upvotes: 1
Views: 71
Reputation: 60034
How do I access the value associated with the variable?
You must 'join' deep in the loop, where the actual computing take place
len([],0).
len([H|T], Sum) :-
dur(H, V), % 'hardcoded' join
Sum is V + Rest.
len(T, Rest),
now the true problem is apparent.
Since a join is such a basic operation in Prolog - really, it does very little otherwise -it's difficult to write - and so reuse - algorithms truly independent from the naming of the data.
Usually 'second order' programming can help, massaging the data to adapt to more generic context. Like
len(Keys, Len) :- maplist(dur, Keys, Nums), sum_list(Nums, Len).
SWI-Prolog autoloads maplist/3 from library(apply), some other Prolog could require you to explicitly load it...
Upvotes: 1