简体   繁体   中英

List of lists reading in prolog

I have a list of lists in prolog in the form

[[Olivia,Thales,Canada Post,Cisco],[Jackson,Thales,Canada Post,Cisco],[Sophia,Cisco,Thales,Canada Post]]

I'm trying to read the list and create a new list which just takes the first element of each sub-list like shown below.

[Olivia, Jackson, Sophia]

So far I'm able to read each element of the list and write it out to the terminal, but once it gets to the last element it fails cause the tail of the list doesn't exist.

This code reads each sub-list but it fails when I reach the last item cause the tail of the list doesn't exist anymore. I tried adding is_list to check if the tail of the list exists but it doesn't seem to be working.

listReading([H|T]) :- write(H), is_list(T),!, nl, listReading(T).

My guess is that the best approach is to read each sub-list and then append the head of the sub-list to a new list however I'm really struggling with just getting the first part right.

I was able to fix my issue myself. Here is the code for the answer:

listReading([], []). listReading([[H|_]|T], [H|T2]) :- listReading(T, T2).

Turns out the answer was fairly simple and I was just overcomplicating my thought process

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM