I have the following problem. I have a certain number of facts such as: parent(jane,dick). parent(michael,dick). And I want to have a predicate such as: numberofchildren(michael,X) so that if I call it like that it shows X=1.
I've searched the web and everyone puts the children into lists, is there a way not to use lists?
Counting number of solutions requires some extra logical tool (it's inherently non monotonic). Here a possible solution:
I can only see two ways to solve this.
The first, which seems easier, is to get all the solutions in a list and count it. I'm not sure why you dislike this option. Are you worried about efficiency or something? Or just an assignment?
The problem is that without using a meta-logical predicate like
setof/3
you're going to have to allow Prolog to bind the values the usual way. The only way to loop if you're letting Prolog do that is with failure, as in something like this:This isn't going to work though; first you're going to get
arguments not sufficiently instantiated
. Then you're going to fix that and get something like this:The reason is that you need Prolog to backtrack if it's going to go through the facts one by one, and each time it backtracks, it unbinds whatever it bound since the last choice point. The only way I know of to pass data across this barrier is with the dynamic store:
I haven't tested this, because I think it's fairly disgusting, but it could probably be made to work if it doesn't. :)
Anyway, I strongly recommend you take the list option if possible.