prolog find minimum value query -


if have facts in following format:

person(name,age). 

how can write query find youngest person?

i have tried using recursion kept getting stuck in infinite loops. far reading done found out need use ! cut operator. appreciated.

you not need use cut operator. i'm hard-pressed imagine solution like.

the simplest thing make query of sort:

youngest(person(name,age)) :-   person(name, age),   \+ (person(name2,age2), name2 \= name, age2 < age). 

this regrettably not efficient, since may have search database once each person, leading o(n^2) performance. should clear why works.

a faster solution use setof/3.

youngest(person(name, age)) :-   setof(age-name, person(name,age), [age-name|_]). 

we're relying on fact setof/3 going sort list , result in youngest person being moved start of result list work. performs better, doesn't read clearly.

there standard library can use solve these sorts of problems swi, i'm not sure if you're using swi , haven't used myself, might it. it's called aggregate.

another approach materialize database directly findall/3 , find minimum directly predicate written that. such solution this:

youngest(person) :-   findall(person(name,age), person(name,age), [p1|rest]),   youngest(p1, rest, person).  youngest(person, [], person). youngest(person(name, age), [person(n2,a2)|rest], person) :-   age < a2 -> youngest(person(name, age), rest, person)             ; youngest(person(n2, a2),    rest, person). 

however, seems lot of work, though gives best performance (should linear time).


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -