Sun Weiran
Sun Weiran

Reputation: 17

Python, why does this function go into an infinite loop

def new_if (pred,then_clause,else_clause):

    if pred:
        then_clause
    else:
        else_clause

def p(x):
    new_if(x>5,print(x),p(2*x))

p(1)

I think the function should stop once x reaches 8 and 8 is printed out.

Thanks a lot for helping

Upvotes: 0

Views: 440

Answers (2)

Bruno
Bruno

Reputation: 122649

There seems to be some general confusion in how you think your code is evaluated: in particular, what you think as predicates and clauses really are not. The arguments are evaluated before the call to new_if is made. Hence, you get a infinite recursive call to p, by evaluating p(2*x) almost as soon as you call p.

You could achieve what you want by passing functions, which you then evaluate within your new_if function. This can be done with lambda functions, like so:

def new_if (pred,then_clause,else_clause):
    if pred():
        then_clause()
    else:
        else_clause()

def p(x):
    new_if(lambda: x>5, lambda: print(x), lambda: p(2*x))

p(1)

In this case, pred, then_clause, else_clause are callables which you need to call (()) for them to be executed.

Upvotes: 2

Ngenator
Ngenator

Reputation: 11259

Your code doesn't do what you think it does.

Every time you call p it executes the code inside that method, which in your case calls new_if with some arguments. However you are evaluating those arguments immediately, which means before entering new_if your code is executing print(x) and p(2*x). This causes p to get called again, repeating the process.

Upvotes: 2

Related Questions