3

I am new to swi-prolog, so basically I have no idea how to write the code... anyway I need to write a precidate about course prerequisite. It will return a list of all courses that are required. And here is my code:

course(cmput325).
course(cmput175).
course(cmput201).
course(cmput204).
prerequisite(cmput204, cmput325).
prerequisite(cmput175, cmput201).
prerequisite(cmput175, cmput204).

/*required(+C,?L)*/

pre(X,C) :- prerequisite(X,C).
pre(X,C) :- prerequisite(X,Y), pre(Y,Z).


pre2(C,L) :-  findall(L1,pre(L1,C),L).

required(C,L) :- sort(pre2(C,L1),L).

I got all correct except the last one required(C,L), pre2(cmput325,L) will returns [cmput204,cmput175], and I want to sort this list, so it will become[cmput175,cmput204]. Then I tried to write a new precidate to deal with it. However, swi-prolog just gave me error:

ERROR: Type error: `list' expected, found `pre2(cmput325,_3718)' (a 
compound)
ERROR: In:
ERROR:    [9] sort(pre2(cmput325,_3770),_3764)
ERROR:    [8] required(cmput325,_3796) at c:/users/mxu3/desktop/a3.pl:19
ERROR:    [7] <user>
Exception: (9) sort(pre2(cmput325, _3322), _3110) ? creep
Exception: (8) required(cmput325, _3110) ? creep

At this stage, I have no idea how to solve this problem... could someone please tell me where should I put this sort command? Thank you....

Code Vanessa
  • 169
  • 6

1 Answers1

3

You see sort( pre2( C,L1), L) as a "nested expression". You expect its inner expression to be evaluated for value, then that value to be substituted in its place and then the outer expression evaluated with that nested result value used in place of the nested expression. Lisp-like languages work this way. Expression evaluation-oriented languages work this way.

Prolog does not work this way. It does not "evaluate" nested "expressions". Instead, Prolog is written in what reminds one of the SSA (static single assignment) style: instead of

sort( nested( expression, nested_result), result)

write

nested(       expression, nested_result), 
sort(                     nested_result,  result)

folks call this "unnesting".

Will Ness
  • 70,110
  • 9
  • 98
  • 181