1
def compose(f, g):
    return lambda x:f(g(x))

def thrice(f):
    return compose(f, compose(f, f))

def repeated(f, n):
    if n == 0:
        return identity
    else:
        return compose(f, repeated(f, n - 1))

def sq(x): return x**2

1) print(thrice(thrice)(sq)(1))

2) print(thrice(thrice(sq)(2))

Can anyone explain to me why the first function returns 1 and the second function does not work? I was thinking thrice(thrice)(sq) will give me sq∘sq∘..... 27 times, so sq(1) is 1^27=1, is that correct? thanks.

7
  • This looks like obfuscated rubbish. Commented Sep 10, 2017 at 3:40
  • 1
    (2) has a syntax error. A closing parenthesis is missing. Also, repeated is never used, why include it into the question? Commented Sep 10, 2017 at 3:42
  • 2
    In Python readability counts. That code counts up to ... 0. Commented Sep 10, 2017 at 3:51
  • What result are you expecting from the second function, exactly? Commented Sep 10, 2017 at 3:54
  • 1
    @coldspped - This is what functional programming looks like in Python ;). Commented Sep 10, 2017 at 3:55

1 Answer 1

1

thrice(thrice)(sq)(x) is an extremely fast growing function:

thrice(thrice)(sq)(1.0000009)
#2.890634480354213e+52
thrice(thrice)(sq)(1.000001)
#1.9497974384856317e+58

When you apply it to a floating point number, it quickly overflows:

thrice(thrice)(sq)(1.000006)
# OverflowError: (34, 'Numerical result out of range')

Edited (thanks to @KarlKnechtel) However, Python implements arbitrary-precision integer numbers. When you apply the function to an integer number (say, thrice(thrice)(sq)(2)), the interpreter calculates the precise answer and then attemps to print it, which, with 40,403,562 decimal places, takes enormous time.

Sign up to request clarification or add additional context in comments.

4 Comments

The result should be 2^(2^27). It doesn't actually take very long on my machine to compute this value (either by OP's method or more directly), but formatting it for printing would take extremely long.
so for the first case, it is 1^(2^27) = 1?
Correct. 1^N is always 1.
i see. Thanks for all of your help :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.