2

I have this list in prolog

[[[dublin, london], 1000], [[dublin, moscow, london], 5000]]

And I want to calculate the minimum of the list such that answer should be

[[dublin, london], 1000]

This question has some similar problem minimum in list of lists in prolog

But that doesn't seems to working I am getting output as false. Please help

gANDALF
  • 360
  • 4
  • 21
  • Notice that at the top of the answer, the author writes: "*First, switch to a better data representation: Instead of `[Key,Value]`, use `Key-Value`!*". – Willem Van Onsem Nov 10 '20 at 19:47
  • I am just looking at tutorials and reading answers ,there is not much of the things available about prolog online ,I really don't know how to get the data in that form :( – gANDALF Nov 10 '20 at 19:49

3 Answers3

3

Try library(aggregate):

?- aggregate_all(min(X,Y), 
       member([Y,X], [[[dublin, london], 1000], 
                      [[dublin, moscow, london], 5000]]), 
       R).
R = min(1000, [dublin, london]).

See also here:

Aggregation operators on backtrackable predicates
https://www.swi-prolog.org/pldoc/man?section=aggregate

1
list_min([],[]) .

list_min([ITEM|ITEMs],MIN)
:-
list_min(ITEMs,ITEM,MIN)
.

list_min([],MIN,MIN) .

list_min([ITEM|ITEMs],MIN0,MIN)
:-
item_min(MIN0,ITEM,MIN1) ,
list_min(ITEMs,MIN1,MIN)
.

item_min(TERM_A,TERM_B,MIN)
:-
TERM_A=[CITIES_A,DISTANCE_A] ,
TERM_B=[CITIES_B,DISTANCE_B] ,
prolog:compare(COMPARE,DISTANCE_A,DISTANCE_B) ,
item_min(COMPARE,TERM_A,TERM_B,MIN) .
.

item_min('<',TERM_A,TERM_B,TERM_A) .
item_min('=',TERM_A,TERM_B,TERM_A) .
item_min('>',TERM_A,TERM_B,TERM_B) .
/*
?- Xs=[[[dublin,london],1000],[[dublin,moscow,london],5000]] , list_min(Xs,MIN) .
Xs = [[[dublin,london],1000],[[dublin,moscow,london],5000]] ,
MIN = [[dublin,london],1000] .

?- Xs=[[[dublin,london],1000],[[dublin,moscow,london],5000],[[a,b],200]] , list_min(Xs,MIN) .
Xs = [[[dublin,london],1000],[[dublin,moscow,london],5000],[[a,b],200]] ,
MIN = [[a,b],200] .

?- Xs=[[[dublin,london],1000],[[a,b],200],[[dublin,moscow,london],5000]] , list_min(Xs,MIN) .
Xs = [[[dublin,london],1000],[[a,b],200],[[dublin,moscow,london],5000]] ,
MIN = [[a,b],200] .

?- 
*/
Kintalken
  • 763
  • 5
  • 9
1

Here's my approach:

min([X],X).
min([H|T],Min):-
    min(T,TMin),
    H>TMin,
    Min is TMin.
min([H|T],Min):-
    min(T,TMin),
    H=<TMin,
    Min is H.

minlist(List,Result):-
    findall(Value, member([_,Value],List),VList),
    min(VList,Min),
    findall(EList,member([EList,Min],List),L),
    append(L,[Min],Result).

?- minlist([[[dublin, london], 1000], [[dublin, moscow, london], 5000]],Result)
Result = [[dublin, london], 1000]
Reema Q Khan
  • 878
  • 1
  • 7
  • 20