Given:
fruitid('Apple', 'Granny Smith', 1).
fruitid('Apple', 'Cox', 2).
fruitid('Pear', 'Bartlett', 3).
How would I go about finding only unique items for instance:
is_unique(FruitName):-
In the example clauses the answer would be Pear.
I’m also trying to add error handling to my code, so in this instance if an input is:
is_unique(pineapple)
How could I catch this and output an error message?
Thanks,
AS
One solution is as follows, using the Prolog negation:
is_unique(X) :- fruitid(X,T1,I1), \+ exists_other_fruit(X,T1,I1). exists_other_fruit(X,T1,I1) :- fruitid(X,T2,I2), (T1,I1) \= (T2,I2).For error handling, you can use the Prolog if/3 operator (defined, e.g., in SICStus Prolog; I don’t know about other Prologs) and do the following:
is_unique2(X) :- if(fruitid(X,T1,I1),\+ exists_other_fruit(X,T1,I1), (print('Unknown Fruit: '), print(X),nl,fail)).The code works as follows:
| ?- is_unique(X). X = 'Pear' ? ; no | ?- is_unique2(X). X = 'Pear' ? ; no | ?- is_unique2('Apple'). no | ?- is_unique2(pineapple). Unknown Fruit: pineapple