Prolog - List into String

2019-08-16 03:26发布

问题:

im done of searching here for a solution but nothing so i decided to ask.

So, i have a query that returns in a list something like this:

List = [6-"read",3-"magazines",3-"music",1-"sport"].

And i need to perform a transformation so do i can get the list like this:

List = [read,magazines,music,sport]. 
or 
List = ["read","magazines","music","sport"].

For that i think i should pass first the to a string to take out the numbers and the '-'. But im struggling with that.

Hope someone can help me! Thanks

回答1:

This looks like homework, so I will not give you the full implementation. What you are looking for is pattern matching in a rule head:

fst_pair(X, pair(X,Y)).

The - operator is just an infix function symbol such that you could write

fst(X, X-Y).

Using this kind of pattern matching it should be easy to write a recursive predicate over the list. It must have a base case for the empty list and a step case for a head followed by the tail of the list:

fsts_list([], []).
fsts_list([ ... | TailFirsts ], [... | Pairs] ) :- % replace ... by some terms
   % possibly insert some predicates here, depending on what you do above
   fst_lists(TailFirsts, Pairs). 

Happy solving!