Categories
Mastering Development

How to use a cut in prolog to find the number of daughters?

Exercise: Observe the family structure below where each person has a gender specification as their third parameter (m = male, f = female).

Use a cut to write the predicate numDaughters(L, Count) in such a way that
family(Husband, Wife, Kids), numDaughters([Husband, Wife|Kids],X) lists each family in the database and the number of daughters in each family.

family(
   person( tom, fox, m, date( 7, may, 1960), works( bbc, 15200) ),
   person( ann, fox, f, date( 9, may, 1961), unemployed),
   [person( pat, fox, f, date( 5, may, 1983), unemployed),
    person( jim, fox, m, date( 5, may, 1983), unemployed) ] ).

family(
   person( henry, stern, m, date( 7, may, 1960), unemployed),
   person( beth, stern, f, date( 9, may, 1961), works( microsoft, 15200)),
   [person( joe, stern, m, date( 6, june, 1985), works( mcdonalds, 9000)),
   person( jeff, stern, m, date( 4, july, 1986), works( arbys, 10000)),
   person( jane, stern, f, date( 19, sep, 1990), unemployed),
   person( jayla, stern, f, date( 19, sep, 1990), unemployed) ] ).

Here’s what I have so far:

female(person(_,_,f,_,_)).
daughter(X):-
 child(X),
 female(X).
  
numDaughters([], 0) :-!.
numDaughters([Head|Tail], Count):-
 daughter(Head), !,
 Count1 is Count+1,
 numDaughters(Tail, Count1)
 ;
 numDaughters(Tail, Count).

I don’t think I am allowed to use child though.

How would I use these predicates to write numDaughters(L, Count) in such a way that
family(Husband, Wife, Kids), numDaughters([Husband, Wife|Kids],X) lists each family in the database and the number of daughters in each family?

Leave a Reply

Your email address will not be published. Required fields are marked *