Returning a true value instead of integer value in prolog -
i have simple function below takes 2 lists ( same size) , variable stores result.
my intention compare first list's head second 1 , increase result one, , return it.
but instead true
/ false
.
myfunction( [], [], 0). myfunction([h1|t1], [h2|t2], n) :- h1 > h2 -> myfunction(t1, t2, n1 + 1); myfunction(t1, t2, n1), n n1 .
you're treating prolog imperative/procedural language, doesn't work way. should read through prolog tutorials and/or books.
in prolog, define predicate defines relation. when define predicate variables, saying that, these variables related in such , such way if.... if prolog succeeds in verifying relation true, predicate response "true" or "yes". otherwise, responds "false" or "no".
here's rework of you're trying do:
my_predicate([], [], 0).
this relation "base case" , says the count of cases corresponding values in first list greater second when lists empty 0.
my_predicate([h1|t1], [h2|t2], n) :- my_predicate(t1, t2, n1), ( h1 > h2 -> n n1 + 1 ; n = n1 ).
this relation says n count of cases corresponding values in first list greater second if n1 count of cases tails, , n n1 + 1 if current head greater, otherwise n n1.
if want make tail recursive efficiency, can use accumulator:
my_predicate(l1, l2, n) :- my_predicate(l1, l2, 0, n). my_predicate([], [], n, n). my_predicate([h1|t1], [h2|t2], a, n) :- ( h1 > h2 -> a1 + 1 ; a1 = ), my_predicate(t1, t2, a1, n).
note above definition of my_predicate/3
assumes want failure if lists different length. if don't want failure in cases, need redefine base case(s).
Comments
Post a Comment