Python Forum

Full Version: Learning functional programming
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi! I decided to apply the functional programming in Python and apply it to the Collatz Conjecture. At first I wrote code for myself in the usual style.
def collatz_steps(n, count=0):
    if n == 1:
        return count
    if n < 1:
        return "Enter numbers from one"
    elif n % 2 == 0:
        return collatz_steps(n / 2, count + 1)
    else:
        return collatz_steps(3 * n + 1, count + 1)


print(collatz_steps(12))
Then I began to convert it line by line. But I ran into the problem already at the beginning. The exit condition from recursion in lambda does not work correctly even for a 1. What's wrong?

def collatz_steps(n, count=0):
    condition = lambda x=n: print("Enter numbers from one") if x == 1 else None
    res = lambda x=n: print(count) if x == 1 else (
        collatz_steps(x / 2, count + 1) if x % 2 == 0 else collatz_steps(3 * x + 1))


print(collatz_steps(12))

Oh, I take it!
def collatz_steps(n, count=0):
    condition = lambda x=n: print("Enter numbers from one") if x < 1 else None
    condition(n)
    res = lambda x=n: count if x == 1 else (
        collatz_steps(x / 2, count + 1) if x % 2 == 0 else collatz_steps(3 * x + 1, count + 1))
    return res(n)


print(collatz_steps(16))
But I'm not sure that this is fully functional programming. Right?
Functional programming isn't about using lambdas. It is about writing programs with functions where something goes in and something goes out, but nothing else happens. The functions don't change anything (no side-effects), they just return a value. From that perspective, your first function is as functional as your second. However, the first one is really better from a functional standpoint. One idea of functional programming is to make things easier to read by not making your guess what changes are happening when you call a function. I think your use of lambdas in the second program makes it harder to read, even though it's not introducing side-effects. Lambdas are inline, single-use functions. If you are giving them names so you can use them across multiple lines, you should really just define a function.
I do functional programming at work and can get behind everything ichabod just said.

That said, I'd be weary of using Python for functional programming, recursion in particular, since it lacks tail call optimization.