prolog - How to find the minimum of the list of the terms? -


i have list of terms below

[t('l', 76), t('i', 73), t('v', 86), t('e', 69)] 

i want write predicate in prolog return term minimum second value. i.e. above list should return t('e', 69)

below tried. not working.

minchar(l, min) :-     setof(t(_, a), member(t(_, a), l), li),     li = [min|_]. 

here output gives above input.

?- minchar([t('l', 76), t('i', 73), t('v', 86), t('e', 69)], min). min = t(_g14650, 69) ; min = t(_g14672, 73) ; min = t(_g14683, 76) ; min = t(_g14661, 86). 

as lurker says, predicates can't start capital letter, fix first.

there 2 basic problems here: first off all, 2 underscores in second line refers different variables, setof/3 doesn't know want same variable both in template , in member/2 call.

second, setof sorts result (which why can extract minimum that), way you've constructed template, sort incorrectly. sorting in swi-prolog uses standard order of terms definition, , in case, you're sorting compound terms of type t(a, b), atom , b number. sort lexicographically first on , on b, not want, want sort on b.

the standard trick here when want sort things key isn't identical term extract key want, bind (-)/2 functor, , sort it. so, example, should work:

minchar(l, min) :-    setof(b-t(a, b), member(t(a, b), l), li),   li = [_-min|_]. 

remember here in prolog, when x - y, you're not doing subtraction, though looks are. binding x , y using (-)/2 functor. subtraction if ask to, using operator forces arithmetic evaluation (such =:=, <, > or is, instance). why 1+1 = 2 false in prolog, because = unification operator, , doesn't arithmetic evaluation.

to clear: don't have use - this, can use whatever functor like. it's traditional use minus functor kind of thing.

edit: also, setof/3 backtrack on free variables not found in template, , since 2 underscores don't refer same free variables, backtrack on every possible assignment second underscore, , throw result away , assign new free variable first underscore. that's why can backtrack on result , bunch of anonymous variables don't know came from.


Popular posts from this blog