Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring symbols in Prolog

Tags:

prolog

I am using this code:

item(one, 50, 40).
item(two, 80, 70).
item(three, 100, 55).
item(four, 50, 45).

maxMeanStudy:-  
    findall(M,item(_,M,_),L),
    max_member(Max,L),
    writeln(Max),!.

To access middle value of item, I have to access it using item(_,M,_). This is OK if there are a few entries only. But if there are many entries it is difficult to enter item(_,_,_,_,_,M,_,_,_,_,_,_,_,_,_,_) every time.

Is there any way that I declare the structure initially as item(Name, Val1, Val2) and then I can just access it with item(Val1)?

like image 363
rnso Avatar asked Dec 05 '22 17:12

rnso


2 Answers

Just define an auxiliary predicate like so:

md_(M) :-
   item(_, M, _).

This way you only have to write that (potentially) large number of underscores once.

Sample query using SICStus Prolog 4.3.3:

| ?- md_(M).
M = 50 ? ;
M = 80 ? ;
M = 100 ? ;
M = 50 ? ;
no
like image 139
repeat Avatar answered Jan 12 '23 04:01

repeat


May be interesting is this code that can work on every arg of a predicate :

item(one, 50, 40).
item(two, 80, 70).
item(three, 100, 55).
item(four, 50, 45).


argStudy(Predicate, Arity, NumArg, Study_Name, V):-
    compound_name_arity(L,Predicate,Arity),
    findall(Args, (L, L =..[_|Args]), L_Args),
    maplist(nth1(NumArg), L_Args, Lst),
    call(Study_Name, Lst, V).

For example :

 ?- argStudy(item, 3, 2, max_list, V).
V = 100.

 ?- argStudy(item, 3, 2, min_list, V).
V = 50.

 ?- argStudy(item, 3, 2, sum_list, V).
V = 280.

 ?- argStudy(item, 3, 1, sort, V).
V = [four, one, three, two].
like image 44
joel76 Avatar answered Jan 12 '23 04:01

joel76