prolog - Check if an element is member of a list -


basically, i'm trying create standard member predicate, in order avoid having load modules project.

this code far, unfortunately isn't working. doing wrong? put cut operator (!) in there make sure worked, doesn't...

/** * checks if element part of list * @param [h|t] list evaluate * @param elem elem check */ memberchecksimple([], _):- !, fail.     /* stop condition */ memberchecksimple([h|t], elem):-   elem \= h,                            /* check if element equals head of list , negate */   memberchecksimple(t, elem).           /* loop */ memberchecksimple(_, _).                /* gets here if elem belongs list */ 

one primary issue logic of predicate overall is failure based , trying make success default of no failure. that's reverse of want logic be. want success based, say, want establish facts , rules describe what's true.

you can play out follows. know if element @ head of list, element of list. following true:

memberchecksimple([h|t], h).   /* h member of [h|t] */ 

it's true element member of list if it's member of tail of list:

memberchecksimple([_|t], h) :- memberchecksimple(t, h). 

these 2 rules need. query doesn't match 1 of above rules fail, want.

now looking @ why failure based predicate isn't working right , succeeding in failure cases, it's because of rule:

memberchecksimple(_, _). 

this says member of anything. you'll have admit, doesn't seem logical (because isn't). considering prior clause cut:

memberchecksimple([], _) :- !, fail. 

this prevents backtracking "universally true" clause if first argument empty list ([]), not if non-empty. example, memberchecksimple([a], b) fail through path in matches second clause, , matches first clause. cut in first clause doesn't prevent memberchecksimple([a], b) backtracking (and succeeding) on third clause. can observe doing trace.

to complete failure based method (which i'll emphasize again, wrong approach problem , has other issues, such not being relational), you'd need cut in second clause:

memberchecksimple([h|t], elem) :-   elem \= h,                    /* check if element equals head of list , negate */   !,   memberchecksimple(t, elem).   /* loop */ 

your comments in code indicate imperative thought process. call "loop" "recursion", example. also, mentioned in comment, argument ordering more naturally stated element followed list since you've named "member" opposed "contains".


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -