List in Prolog with elements in round brackets

元气小坏坏 提交于 2019-12-24 20:26:13

问题


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


回答1:


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 .




回答2:


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
| ?-


来源:https://stackoverflow.com/questions/48130976/list-in-prolog-with-elements-in-round-brackets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!