Predicates

Hi, The definition of a predicate is not clear to me. From the books, they say that a predicate is a function that returns a Boolean or a value that can be converted to a Boolean. The following functios return Boolean and they even receive the same type of parameter. But the 2nd one is not a predicate. Is it because of the count variable in the return statement?

a predicate
1
2
bool check1( int a )
{ return a > 10; }


not a predicate
1
2
3
4
5
bool check2( int b )
{
    static int count = 0;
    return ( b + count++ ) % 2 == 0; // even numbers
}


Thanks.
Well, i have no idea what a predicate is, but i can tell you what check2 does

Everytime you call it, count is increased by one, and because count is static, it will not delete the variable when the function returns, it will, keep its value

so for example, if youd call it with b as 0
1
2
3
4
5
6
check2(0) // 0 % 2 == 0 -> true;  count++; (first time calling check2)
check2(0) // 1 % 2 == 0 -> false; count++;
check2(0) // 2 % 2 == 0 -> true;  count++;
check2(0) // 3 % 2 == 0 -> false; count++;
check2(0) // 4 % 2 == 0 -> true;  count++;
check2(0) // 5 % 2 == 0 -> false; count++; 

everytime you call check2, with the same value, you will get a different result
Last edited on
All above about is a true, but it's vital to add 'return value of predicate depends only on input parameters' . It means that if you call the predicate function with same value you must receive the same results. This rule is broken in the second example, you can see it if you call it twice with equal parameter. And if we continue this discussion it's clear that predicate can't hold any state(the second example has static variable).

I hope it's clear.
Last edited on
It's now clear. Thanks.
Topic archived. No new replies allowed.