Difficulty in defining a higher-order function to mimic if statement
<p>I have been hard pressed to answer a question we were recently asked as part of an exercise on higher-order functions in Python.</p>

<p>The question is to define two functions, one which takes no arguments, and passes three globally defined functions, c(), t() and f(), through if/else statements (if <code>c()</code> true, return <code>t()</code> else return <code>f()</code>). The other function is a higher-order function that we evaluate on <code>c()</code>, <code>t()</code> and <code>f()</code> that then passes them through the same if/else statements. </p>

<p>These functions are different and our task is to see how by defining three functions <code>c()</code>, <code>t()</code> and <code>f()</code> such that the first function returns 1 and the second returns something other than one.</p>

<p>So far I have come to the realization that the issue lies with the calling of the functions <code>c()</code>, <code>t()</code> and <code>f()</code> before passing them through the if/else statements. This however has not been enough to inspire a solution. Would anyone be able to steer me in the correct direction?</p>

<p>Here is the associated code:</p>

<pre><code>def if_function(condition, true_result, false_result):

    if condition:
        return true_result
else:
    return false_result


def with_if_statement():

    if c():
        return t()
    else:
        return f()

def with_if_function():

    return if_function(c(), t(), f())

def c():
    return []

def t():
    return 1

def f():
    return 1
</code></pre>

<p>You may easily pass callable as function arguments, without calling them.</p>

<pre><code>def cond():
    return True

def f():
    return 2

def g():
    time.sleep(60)

def if_function(condition_callable, call_if_true, call_if_false):
    if condition_callable():
        return call_if_true()
    else:
        return call_if_false()

if_function(cond, f, g)  # evaluates immediately, does not sleep since g is never evaluated.
</code></pre>

python if-statement higher-order-functions