Find the max element and its index in a list - Prolog -


i fresh in prolog. , trying write predicate finds max value , index of list of integers. i.e max_list([2,3,4], max, index) yield max=4, index=2

thank reply~ apologize! first time ask questions in stackoverflow. write predicate find maximum or minimum of list, don't know how exact position value in list. trying comprehend answers.

using ...

:- use_module(library(clpfd)). 

..., maplist/2, , nth0/3 define:

zs_maximum_at(zs,max,pos) :-    maplist(#>=(max),zs),    nth0(pos,zs,max). 

here's query op gave:

?- zs_maximum_at([2,3,4],m,i). = 2, m = 4. 

ok! ... how most general query?

?- zs_maximum_at(zs,m,i).   zs = [m], = 0, m in inf..sup ; zs = [ m,_b], = 0, m #>= _b ; zs = [_a, m], = 1, m #>= _a ; zs = [ m,_b,_c], = 0, m #>= _b, m #>= _c ; zs = [_a, m,_c], = 1, m #>= _a, m #>= _c ; zs = [_a,_b, m], = 2, m #>= _a, m #>= _b ; zs = [ m,_b,_c,_d], = 0, m #>= _b, m #>= _c, m #>= _d ; zs = [_a, m,_c,_d], = 1, m #>= _a, m #>= _c, m #>= _d ... 

edit: arithmetic expressions?

  1. we can allow use of arithmetic expressions adding additional goal (#=)/2:

     zs_maximum_at(zs,expr,pos) :-    maplist(#>=(max),zs),    nth0(pos,zs,expr),    expr #= max. 

    now can run queries following one—but lose monotonicity (cf. this clpfd manual)!

     ?- zs_maximum_at([0+1,1+1,2-0,3-1,1+0],m,i).   = 1, m = 1+1 ; = 2, m = 2-0 ; = 3, m = 3-1 ; false. 
  2. to disable arithmetic expressions can use length/2 in combination ins/2:

     zs_maximum_at(zs,max,pos) :-    length(zs,_),    zs ins inf..sup,    maplist(#>=(max),zs),    nth0(pos,zs,max). 

    running above query again, get:

     ?- zs_maximum_at([0+1,1+1,2-0,3-1,1+0],m,i). error: type error: `integer' expected, found `0+1' (a compound) 

note issue (of allowing arithmetic expressions or not) not limited .
it present when using plain-old prolog arithmetic predicates is/2 , friends.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -