Search code examples
functional-programminglambda-calculus

How to fix the infinite loop error of "f = lambda x: f(x)+1" in a functional programming language?


Consider the following code in python:

f = lambda x: x

f = lambda x: f(x)+1

f(1)

Python throws an "infinite loop" error while running the last line, which is clear in the way that it interprets the second line as a recursive formula for f.

But the second line seems resonable if one substitutes the 'value' of f in the right side, and then assigns the resulting function to f (in the left).

Does there exists a straightforward way for fixing this error in python (or another language which can work with functions) via lambda calculus operations?

I asked this question just for curiosity to know much more about functional languages, but it seems to me that the answer helps to produce loop calculations on functions!


Solution

  • Sure. In Lisp/Scheme family, you can use let* for this purpose:

    (let* ((f (lambda (x) x))
           (f (lambda (x) (+ (f x) 1))))
      (display (f 1)))
    

    Note that you'll find Scheme syntax to be much closer to lambda-calculus, aside from the prefix notation. The let* construct sequentially defines names, allowing the fist name to be used in the body of the second, even if you "shadow" it.

    In Python, you'll have to name the functions separately, something like this:

    f0 = lambda x: x
    f1 = lambda x: f0(x) + 1
    print(f1(1))
    

    If you want to study lambda-calculus, especially the untyped kind, Scheme is your best choice as most lambda-calculus constructs will map directly to it, modulo the prefix syntax. For typed lambda-calculus, a good choice would be a language like Haskell. I personally wouldn't use Python to study functional programming, as it conflates the two styles in ways that will prove to be a hindrance; though of course it's doable.