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