3

How to convert this

fact( [a,b,c], [d,e,f], ..., [p, q, r] )

to a list of these elements?

Result:

[[a,b,c], [d,e,f], ..., [p, q, r]]
balping
  • 7,518
  • 3
  • 21
  • 35

2 Answers2

3
list_fact_args(Fact,List) :- Fact =.. [fact|List].

=.. is a handy predicate that transforms the predicate on the left to a list with predicate name as the first member and its arguments as the latter members. Or a list on a right to the predicate on the left. Here fact denotes that it lists only the predicates named 'fact'.

traitor
  • 318
  • 1
  • 6
  • I don't think Visual Prolog has the `=../2` operator. – lurker Feb 09 '14 at 22:02
  • Sorry but how to use this?
    `fact( [a,b,c], [d,e,f], [p, q, r] ).`
    `list_fact_args(Fact,List) :- Fact =.. [fact|List].`
    `list_fact_args(F,L)`
    `No solutions`
    – balping Feb 09 '14 at 22:46
  • @mbratch Visual prolog does have that operator – balping Feb 09 '14 at 22:48
  • 1
    Like this: `list_fact_args(fact( [a,b,c], [d,e,f], [p, q, r] ),L)`. Sorry for being too succinct. I'm new here. – traitor Feb 09 '14 at 23:10
  • No problem, and thank you very much!! One more thing (sorry, I'm a newbie to prolog): what if fact(....) is predefined like `fact( [a,b,c], [d,e,f], [p, q, r] ).` – balping Feb 09 '14 at 23:29
  • @balping ok, cool. I was going to suggest it, but I couldn't spot it in their online documentation. – lurker Feb 10 '14 at 02:15
  • 1
    @balping if you *only* need to get a list of the arguments for a particular predicate whose arity is known, then you can just put the arguments into a list. E.g., if you have `fact` defined as you say, then, given `fact(A, B, C), List = [A, B, C]`, `List` will instantiate to `[[a,b,c], [d,e,f], [p,q,r]]`. Otherwise, using `=../2` is the way to go! It's great fun to work with. – Shon Feb 10 '14 at 06:44
  • @aBathologist I mean the user inputs only this: `fact( [a,b,c], [d,e,f], ..., [p, q, r] )` And I have to handle somehow the list – balping Feb 10 '14 at 18:20
  • @balping meaning you don't know the arity (number of arguments) or the functor (e.g., `fact`)? In which case you want to use `=../2`. – Shon Feb 10 '14 at 20:46
  • @aBathologist I don't know the number of arguments. – balping Feb 11 '14 at 17:22
0

Get your Prolog Manual or textbook and look up =.. / 2.

jschimpf
  • 4,904
  • 11
  • 24