Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog - Search a list for an element, print the list if element is found

Tags:

list

prolog

So I am trying to write a small program that does the following.

I can search for a element inside a list, if the element is found in the list, then the list is printed out to confirm that it has been found.

So in basic pseudo -

  1. list of elements - computer, mouse, keyboard, webcam
  2. search for mouse in this list
  3. output the list which mouse has been found in

While doing some reading I found something which does what I want to do pretty much. This is below

on(Item,[Item|Rest]).  

on(Item,[DisregardHead|Tail]):-
on(Item, Tail). 

If I type the query - on(apples, [pear, grape, banana, plum, apples]). then it searches through the list, discarding non-relevant elements until it comes to the end and succeeds.

What I want to do is write my own list in the editor and work from it by doing the same kind of function to it like above.(Rather than just inputting the list as a query into the console.)

Thanks

like image 756
Chris Avatar asked Nov 19 '12 14:11

Chris


Video Answer


2 Answers

You can define in your program

list_of_my_elements([pear, grape, banana, plum, apples]).

in_my_list_of_elements(X) :- 
    list_of_my_elements(L),
    member(X, L).

Then query

?- in_my_list_of_elements(apple).

I wouldn't re-implement and rename the member predicate.

like image 105
NotAUser Avatar answered Oct 02 '22 02:10

NotAUser


domains x = integer l = integer*

predicates find(l,x)

clauses

find([],N) :-
    write("There is no such element in the list"),nl.

find([Element|List],1) :-
    write("The element is ",Element),nl.

find([Element|List],N) :-
    N1 = N-1,
    find(List,N1).

Output :

Goal: find([1,2,3,4],3) The element is 3 Yes

Goal: find([1,2,3,4],0) There is no such element in the list Yes

Goal: find([1,2,3,4],5) There is no such element in the list Yes

Goal: find([1,2,4,3],4) The element is 3 Yes

like image 42
Prohollad Sarkar Avatar answered Oct 02 '22 01:10

Prohollad Sarkar