Prolog program to find elements from the list

  • A program to find a given element from the list:
    domains
         namelist = name*
         name = symbol
    
    predicates
         member(name,namelist)
         go
       
    clauses
         go:-
         readln(X),
         member(X,[a,s,d,f,g,h,j]).
         
         member(Name,[Name|_]).
         member(Name,[_|Tail]) if member(Name,Tail).
    
  • Finding the last element from the list:
    domains
    	namelist = name*
    	name = symbol
    predicates
    	traverse(namelist)
    clauses
    	traverse([]).
    	
    	traverse([Head|Tail]):-
    	Tail=[],
    	write(Head),nl.
    	
    	traverse([_|Tail]):-
    	
    	traverse(Tail).
    	
    
  • Finding the N th element from the list:

    domains
              namelist=symbol*
    
    predicates
               n_element(namelist,integer,symbol)
               clauses
               n_element([Head|_],1,X):-
               X=Head.
               n_element([_|Tail],N,X):-
               NN=N-1,
               n_element(Tail,NN,X).
    
    

    also try with:

    domains
    	namelist = name*
    	name = symbol
    predicates
    	traverse(integer,integer,namelist)
    	go
    clauses
    go:-
    readint(X),
    traverse(1,X,[a,s,d,f,g,h,j,k,l]).
    	
    traverse(A,B,[_|Tail]):-
    	A<B,
    	C=A+1,
    	traverse(C,B,Tail).
    	
    	
    	traverse(A,B,[Head|_]):-
    	A=B,
    	write(Head).
    	
  • One thought on “Prolog program to find elements from the list

    Leave a Reply

    Please log in using one of these methods to post your comment:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out /  Change )

    Google photo

    You are commenting using your Google account. Log Out /  Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out /  Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out /  Change )

    Connecting to %s