1

Say I have a predicate pred containing several facts.

pred(a, b, c).
pred(a, d, f).
pred(x, y, z).

Can I use findall/3 to get a list of all facts which can be pattern matched?

for example, if I have

pred(a, _, _) I would like to obtain

[pred(a, b, c), pred(a, d, f)]

bsky
  • 19,326
  • 49
  • 155
  • 270
  • You mean like this? `findall( p(a, X, Y), pred(a, X, Y), L).`? I'm probably oversimplifying what you're asking... – lurker Jan 13 '14 at 02:36
  • @mbratch this will result in something of the form `[pred(a, _801, _802), pred(a, _901, _902)]`, so with unbounded variables – bsky Jan 13 '14 at 02:50
  • 1
    When I run `findall( p(a, X, Y), pred(a, X, Y), L).` with swipl I get `[p(a,b,c), p(a,d,f)]`. Did you try it? Exactly what are you wanting to supply for inputs? I'm not sure if sicstus-prolog behavior of `findall` may be a little different. – lurker Jan 13 '14 at 02:52
  • 4
    Note that if you run it with underscores, like `findall(p(a,_,_), pred(a,_,_), L).` you'll see the results you mentioned since those are anonymous variables and can't be instantiated. I can reproduce your result running it that way. You need the `X` and `Y` in place to get instantiation. – lurker Jan 13 '14 at 02:59
  • I neglected to mention, you can use the same functor as your fact, so this also works: `findall(pred(a,X,Y), pred(a,X,Y), L).`. – lurker Jan 13 '14 at 11:49

1 Answers1

1

Just summing up what @mbratch said in the comment section:

Yes, but you have to make sure that you either use named variables or construct a simple helper predicate that does that for you:

Named variables:

findall(pred(a,X,Y),pred(a,X,Y),List).

Helper predicate:

special_findall(X,List):-findall(X,X,List).

?-special_findall(pred(a,_,_),List).
List = [pred(a, b, c), pred(a, d, f)].

Note that this doesn't work:

findall(pred(a,_,_),pred(a,_,_),List).

Because it is equivalent to

 findall(pred(a,A,B),pred(a,C,D),List).

And thus doesn't unify the Variables of Template with those of Goal.

Patrick J. S.
  • 2,885
  • 19
  • 26