0

The structure of the facts is

  %structure
 student(ID,FirstName,LastName,[courseList]).
 course(CourseCode,CourseTtile,Credits,Level).

Following is the fact.

 student(20135639,'Mohammed','Abdul Wahab',
 [course('ITIS411','DATABASE SYSTEM IMPLEMENTATION',3,hard),
 course('ITIS412','INFORMATION SECURITY',3 ,easy),
 course('ITIS499','SENIOR PROJECT',3,hard),
 course('ITIS469','AI',3,hard)] ).

I want to write a rule that sums the credits hours from the list

sum([],0).
sum(H|T,S):-
sum(T,S1),
 S is H + S1.


sumCr(Id, Cr):-
    student(Id,_,_,Courselist),
    sum(Courselist,Cr).    

The above rule sums all the elements of the facts in the list but I want to sum only the Cr value of all facts in the list. So when i run the following query, the output should be.

 ?. sumCr(20135639, Cr).
    Cr=12.      
lurker
  • 56,987
  • 9
  • 69
  • 103
Far
  • 341
  • 2
  • 11
  • 25
  • `sum` doesn't sum anything; it yields `0` for an empty list and an unbound variable for any longer list. – Scott Hunter May 27 '17 at 14:40
  • I have corrected the mistake @ScottHunter – Far May 27 '17 at 14:44
  • 1
    `sum(H|T,S)` has syntax issues. Also, your `sum/2` is intended to sum a list of integers, but you're passing it a list of course names (or something, it's not clear). – lurker May 27 '17 at 14:49

1 Answers1

0

You just need to extract the part of each course you want to sum:

sum( [], 0 ).
sum( [course(_,_,N,_)|T], Sum ) :-
    sum( T, NT ),
    Sum is NT + N.
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101