Prolog: Writing each element of an existing list - 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).

Related

Parsing list of items with DCG?

How do you parse string which is list of items f.e.
1,2,3,4
aa,b,ccc,ddd
Currently I do this (and is the comma) :
sub(X,Y) --> req(X), [and], req(Y).
sub(X) --> req(X).
req(on(X,Y)) --> [X,is,on,the,Y],!.
req(on(X,Y)) --> [X,is,on,Y],!.
req(on(X,Y)) --> [X,on,Y],!.
req(isa(X,Y)) --> [X,is,a,Y].
?- phrase(sub(T,U),[box,is,on,the,table, and, box,is,a,object], R).
T = on(box, table),
U = isa(box, object),
R = [].
but in this case sub() have two different heads sub(X) and sub(X,Y) , which messes the higher level.
I did this :
sub([X|Y]) --> req(X), [and], sub(Y).
sub([X]) --> req(X).
which seems to work ... but returns too many results ..??
?- phrase(sub(T),[box,is,on,the,table, and, box,is,a,object, and, apple , is,a,fruit], R).
T = [on(box, table), isa(box, object), isa(apple, fruit)],
R = [] ;
T = [on(box, table), isa(box, object)],
R = [and, apple, is, a, fruit] ;
T = [on(box, table)],
R = [and, box, is, a, object, and, apple, is, a|...].
it should stop at the first results ...!!
ooo i have to reverse the order, right ?
sub([X]) --> req(X).
sub([X|Y]) --> req(X), [and], sub(Y).
With your last definition:
sub([X]) --> req(X).
sub([X|Y]) --> req(X), [and], sub(Y).
The following queries work:
?- phrase(sub(Sub), [box,is,on,the,table, and, box,is,a,object]).
Sub = [on(box, table), isa(box, object)] ;
false.
?- phrase(sub(Sub), [box,is,on,the,table, and, box,is,a,object, and, apple,is,a,fruit]).
Sub = [on(box, table), isa(box, object), isa(apple, fruit)] ;
false.
Note that I only give two arguments to phrase. phrase has a form with two arguments, and one with three arguments. As a beginner, you will almost certainly only want to use the two-argument form. The two-argument form parses the entire list you give it and succeeds only if really everything in the list could be parsed. This is almost certainly what you want as a beginner. The three-argument form allows you to parse only the beginning of a list, then get back the suffix that wasn't parsed. You are not advanced enough to need this.

Prolog how to use if / else in this way?

In Prolog, i want to use an if-else statement in the following way:
lecture(spanish,monday,at8).
lecture(french,monday,at8).
lecture(english,monday,at10).
lecture(german,tuesday,at8).
generatePossibleSchedulesWithTwoLectures(LectureA,LectureB):-
lecture(LectureA,A,X),
lecture(LectureB,B,Y),
%If A of LectureA is equal to B of lectureB -> times must be un-equal
% How to do implement the requirement of the line above here?
As a result, the function should generate schedules with two lectures which are not in the same time slot.
You started by assuming, i want to use an if-else statement in the following way, but the logic of your problem doesn't describe an if-then-else condition. An if-then-else isn't the construct you want to achieve your goal of:
Generate schedules with two lectures which are not in the same time slot
Also, the Prolog if-then-else construct A -> B ; C removes the choice point you are after. For some detail on this, see the answer to, What's the meaning of Prolog operator '->'
What you really want is to say:
A schedule two lectures A & B is valid if Day1 and Time1 are a time slot for A, and Day2 and Time2 are a time slot for B, and time slots Day1-Time1 and Day2-Time2 are different.
If fact, to avoid duplicates and to keep the schedule in chronological order, we can enforce that the "first" time slot is earlier than the second. This translates to:
generate_possible_schedules_with_two_lectures(LectureA, LectureB):-
lecture(LectureA, Day1, Time1),
lecture(LectureB, Day2, Time2),
dif(LectureA, LectureB), % don't schedule the same class
Day1-Time1 #< Day2-Time2 % timeslots in order, and different
We simplify the time slot comparison by forming a term A-B with the day and time. You could do the longer comparison, comparing the day and tie individually, replacing Day1-Time1 #< Day2-Time2 with (Day1 #< Day2 ; Day1 == Day2, Time1 #< Time2). In either case, you get the following results with your data:
?- generate_possible_schedules_with_two_lectures(A, B).
A = spanish,
B = german ;
A = french,
B = german ;
A = english,
B = spanish ;
A = english,
B = french ;
A = english,
B = german ;
false.

prolog, i have list of structure how to Extract data and return new list of other structure?

I implementing Family program in prolog i have a problem to implement some rules.
first of all i implement this rule:
number_of_children_couple(_list):-
findall(children(_f,_m,_n),children(_f,_m,_n),_list).
return list:
19 ?- number_of_children_couple(_list).
_list = [children(mordechai, miriam, 1), children(salax, naima, 1), children(eli, bella, 2), children(..., ..., ...)|...].
my problem is how to implement :
number_of_children_person(_list28,list_person):-
first argument:
_list28 = _list //the above list ,that return from the rule
and second argument is :
list_person = [children(mordechai, 1), children(salax, 1),children(eli, 2),children(..., ...)|...]
and i also use with:
%_num is number of children for couple
children(_father,_mother,_num):-
couple(_mother,_father),
findall(_child,parents(_mother,_father,_child),_children),
length1(_children,_num).
%_num is number of children for _person
children(_person,_num):-
gender(_person,_),
findall(_child,parent(_person,_child),_list),
length1(_list,_num).
if what you want is to drop an argument from children/3 structure, can be done in a number of ways, the simpler being
number_of_children_person([],[]).
number_of_children_person([children(A,_,C)|R],[children(A,C)|T]) :-
number_of_children_person(R,T).
or more succintly
number_of_children_person(L3,L2) :-
findall(children(A,C), member(children(A,B,C),L3), L2).

Multiple lists of the same length to csv

I have a couple List<string>s, with the format like this:
List 1 List 2 List 3
1 A One
2 B Two
3 C Three
4 D Four
5 E Five
So in code form, it's like:
List<string> list1 = {"1","2","3","4","5"};
List<string> list2 = {"A","B","C","D","E"};
List<string> list3 = {"One","Two","Three","Four","Five"};
My questions are:
How do I transfom those three lists to a CSV format?
list1,list2,list3
1,A,one
2,b,two
3,c,three
4,d,four
5,e,five
Should I append , to the end of each index or make the delimeter its own index within the multidimensional list?
If performance is your main concern, I would use an existing csv library for your language, as it's probably been pretty well optimized.
If that's too much overhead, and you just want a simple function, I use the same concept in some of my code. I use the join/implode function of a language to create a list of comma separated strings, then join that list with \n.
I'm used to doing this in a dynamic language, but you can see the concept in the following pseudocode example:
header = {"List1", "List2", "List3"}
list1 = {"1","2","3","4","5"};
list2 = {"A","B","C","D","E"};
list3 = {"One","Two","Three","Four","Five"};
values = {header, list1, list2, list3};
for index in values
values[index] = values[index].join(",");
values = values.join("\n");

Erlang record item list

For example i have erlang record:
-record(state, {clients
}).
Can i make from clients field list?
That I could keep in client filed as in normal list? And how can i add some values in this list?
Thank you.
Maybe you mean something like:
-module(reclist).
-export([empty_state/0, some_state/0,
add_client/1, del_client/1,
get_clients/1]).
-record(state,
{
clients = [] ::[pos_integer()],
dbname ::char()
}).
empty_state() ->
#state{}.
some_state() ->
#state{
clients = [1,2,3],
dbname = "QA"}.
del_client(Client) ->
S = some_state(),
C = S#state.clients,
S#state{clients = lists:delete(Client, C)}.
add_client(Client) ->
S = some_state(),
C = S#state.clients,
S#state{clients = [Client|C]}.
get_clients(#state{clients = C, dbname = _D}) ->
C.
Test:
1> reclist:empty_state().
{state,[],undefined}
2> reclist:some_state().
{state,[1,2,3],"QA"}
3> reclist:add_client(4).
{state,[4,1,2,3],"QA"}
4> reclist:del_client(2).
{state,[1,3],"QA"}
::[pos_integer()] means that the type of the field is a list of positive integer values, starting from 1; it's the hint for the analysis tool dialyzer, when it performs type checking.
Erlang also allows you use pattern matching on records:
5> reclist:get_clients(reclist:some_state()).
[1,2,3]
Further reading:
Records
Types and Function Specifications
dialyzer(1)
#JUST MY correct OPINION's answer made me remember that I love how Haskell goes about getting the values of the fields in the data type.
Here's a definition of a data type, stolen from Learn You a Haskell for Great Good!, which leverages record syntax:
data Car = Car {company :: String
,model :: String
,year :: Int
} deriving (Show)
It creates functions company, model and year, that lookup fields in the data type. We first make a new car:
ghci> Car "Toyota" "Supra" 2005
Car {company = "Toyota", model = "Supra", year = 2005}
Or, using record syntax (the order of fields doesn't matter):
ghci> Car {model = "Supra", year = 2005, company = "Toyota"}
Car {company = "Toyota", model = "Supra", year = 2005}
ghci> let supra = Car {model = "Supra", year = 2005, company = "Toyota"}
ghci> year supra
2005
We can even use pattern matching:
ghci> let (Car {company = c, model = m, year = y}) = supra
ghci> "This " ++ c ++ " " ++ m ++ " was made in " ++ show y
"This Toyota Supra was made in 2005"
I remember there were attempts to implement something similar to Haskell's record syntax in Erlang, but not sure if they were successful.
Some posts, concerning these attempts:
In Response to "What Sucks About Erlang"
Geeking out with Lisp Flavoured Erlang. However I would ignore parameterized modules here.
It seems that LFE uses macros, which are similar to what provides Scheme (Racket, for instance), when you want to create a new value of some structure:
> (define-struct car (company model year))
> (define supra (make-car "Toyota" "Supra" 2005))
> (car-model supra)
"Supra"
I hope we'll have something close to Haskell record syntax in the future, that would be really practically useful and handy.
Yasir's answer is the correct one, but I'm going to show you WHY it works the way it works so you can understand records a bit better.
Records in Erlang are a hack (and a pretty ugly one). Using the record definition from Yasir's answer...
-record(state,
{
clients = [] ::[pos_integer()],
dbname ::char()
}).
...when you instantiate this with #state{} (as Yasir did in empty_state/0 function), what you really get back is this:
{state, [], undefined}
That is to say your "record" is just a tuple tagged with the name of the record (state in this case) followed by the record's contents. Inside BEAM itself there is no record. It's just another tuple with Erlang data types contained within it. This is the key to understanding how things work (and the limitations of records to boot).
Now when Yasir did this...
add_client(Client) ->
S = some_state(),
C = S#state.clients,
S#state{clients = [Client|C]}.
...the S#state.clients bit translates into code internally that looks like element(2,S). You're using, in other words, standard tuple manipulation functions. S#state.clients is just a symbolic way of saying the same thing, but in a way that lets you know what element 2 actually is. It's syntactic saccharine that's an improvement over keeping track of individual fields in your tuples in an error-prone way.
Now for that last S#state{clients = [Client|C]} bit, I'm not absolutely positive as to what code is generated behind the scenes, but it is likely just straightforward stuff that does the equivalent of {state, [Client|C], element(3,S)}. It:
tags a new tuple with the name of the record (provided as #state),
copies the elements from S (dictated by the S# portion),
except for the clients piece overridden by {clients = [Client|C]}.
All of this magic is done via a preprocessing hack behind the scenes.
Understanding how records work behind the scenes is beneficial both for understanding code written using records as well as for understanding how to use them yourself (not to mention understanding why things that seem to "make sense" don't work with records -- because they don't actually exist down in the abstract machine...yet).
If you are only adding or removing single items from the clients list in the state you could cut down on typing with a macro.
-record(state, {clients = [] }).
-define(AddClientToState(Client,State),
State#state{clients = lists:append([Client], State#state.clients) } ).
-define(RemoveClientFromState(Client,State),
State#state{clients = lists:delete(Client, State#state.clients) } ).
Here is a test escript that demonstrates:
#!/usr/bin/env escript
-record(state, {clients = [] }).
-define(AddClientToState(Client,State),
State#state{clients = lists:append([Client], State#state.clients)} ).
-define(RemoveClientFromState(Client,State),
State#state{clients = lists:delete(Client, State#state.clients)} ).
main(_) ->
%Start with a state with a empty list of clients.
State0 = #state{},
io:format("Empty State: ~p~n",[State0]),
%Add foo to the list
State1 = ?AddClientToState(foo,State0),
io:format("State after adding foo: ~p~n",[State1]),
%Add bar to the list.
State2 = ?AddClientToState(bar,State1),
io:format("State after adding bar: ~p~n",[State2]),
%Add baz to the list.
State3 = ?AddClientToState(baz,State2),
io:format("State after adding baz: ~p~n",[State3]),
%Remove bar from the list.
State4 = ?RemoveClientFromState(bar,State3),
io:format("State after removing bar: ~p~n",[State4]).
Result:
Empty State: {state,[]}
State after adding foo: {state,[foo]}
State after adding bar: {state,[bar,foo]}
State after adding baz: {state,[baz,bar,foo]}
State after removing bar: {state,[baz,foo]}