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:
Query:
writeln/1
is simplywrite/1
followed bynl
.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 calledmaplist
for doing the work for you:And you would call it like so:
The long-hand recursive form would be similar to what was given in the other answer:
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: