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 -
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With