List in Prolog with elements in round brackets

2019-08-19 22:56发布

Good Morning

I have list similiar to this: [(1-4), (2-4), (3-4)]. I'd like to write only first/second/third part of round bracket. I wrote a function:

write_list([]).

write_list([Head|Tail]) :-
  write(Head), nl,
  write_list(Tail).

It only writes whole round bracket:
1-4
2-4
3-4

I'd like my output to be the 1st element of round bracket:
1
2
3

I'll be grateful for any help :D

标签: list prolog
2条回答
神经病院院长
2楼-- · 2019-08-19 23:54

Here you are:

write_list([]).
write_list([(A-_)|Tail]) :-
  writeln(A),
  write_list(Tail).

Query:

?- write_list([(1-4),(2-4),(3-4)]).
1
2
3
true

writeln/1 is simply write/1 followed by nl .

查看更多
趁早两清
3楼-- · 2019-08-19 23:56

You don't really want to write the results but provide them as an argument. Many beginners in Prolog get stuck on this point. Also, it's such a common pattern to apply the same logic to each list element that Prolog has a predicate called maplist for doing the work for you:

first_subterm(A-_, A).   % First subterm of `A-_` is `A`

first_subterms(PairList, FirstSubTerms) :-
    maplist(first_subterm, PairList, FirstSubTerms).

And you would call it like so:

| ?- first_subterms([(1-4), (2-4), (3-4)], FirstSubTerms).

FirstSubTerms = [1,2,3]

yes
| ?-

The long-hand recursive form would be similar to what was given in the other answer:

first_subterms([], []).  % The list of first subterms of [] is []
first_subterms([(A-_)|Pairs], [A|SubTerms]) :-
    first_subterms(Pairs, SubTerms).

Note that the "round brackets" are parentheses and, in Prolog, in this context only perform a grouping of the term. It turns out that [(1-4), (2-4), (3-4)] here behaves the same, therefore, as [1-4, 2-4, 3-4] since the , is lower precedence than - in the list notation. So this is also the behavior:

| ?- first_subterms([1-4, 2-4, 3-4], FirstSubTerms).

FirstSubTerms = [1,2,3]

yes
| ?-
查看更多
登录 后发表回答