简体   繁体   中英

Prolog: Writing each element of an existing list

I'm trying to do two things. (1) display each element of an existing list, and (2) search a list to display all names that contain that element.

Here are some facts:

 classes(hannes, [cs490, cs499, cs413]).   % name has this list of classes
 classes(tony, [ma330, ma211, ma250]).
 classes(nicholas, [cs424, cs570, ma330]).
 classes(pj, [ma211, ma250, ma285, cs424]).
 classes(inga, [cs285, cs307, cs309]).
 classes(christine, [ma285, ma211, ma330]).
 classes(lisa, [cs424, cs413, cs490]).
 classes(marty, [cs570, cs424]).

And, here is my rule so far:

 taking(N,C) :-               % student Name N is taking class C
      classes(N,Cs),
      [C|T] = Cs.

At the moment, I know this only takes the head of the list and displays it. I need to display each item of the list (one line at a time, if easy enough to do, but not important). But, I also need to be able to do it in reverse. If 1 course is queried (ma330), I want it to display all students that have that particular course.

Query example 1:

?- taking(nicholas, Classes).
Classes = [cs424, cs570, ma330] ;

OR

?- taking(nicholas, Classes).
Classes = cs424 ;
Classes = cs570 ;
Classes = ma330 ;

Query example 2:

?- taking(Names, ma330).
Names = tony ;
Names = nicholas ;
Names = christine ;

I'm going to keep searching for a resolution, but if anyone can help, it would be appreciated.

Thank you!!!

Think of that : C is member of Classes.

EDIT OK try this code :

taking(N,C) :-               % student Name N is taking class C
      classes(N,Cs),
      member(C, Cs).

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