If your question is “give me some examples showing how FP works in python” then:
What is pure functional programming (in Python)?
This is a programming paradigm that avoids state and mutable data and instead relies on the return values of a function. This means that a purely functional program written in python will not have such things as variables, states, etc.
Not very clean FP
You can combine FP and the imperative paradigm with good results (see here ). The linked gist is a math quiz program that I did for the python class that I took a few months ago. Feel free to do whatever you want with the code.
FP in Java / C #
I personally have no experience with C #, so someone else would need to post a C # example, but you can have FP in Java, but not purely FP. Example:
int fib (int x) { if (x < 2) return x; return fib (x-1) + fib(x-2); }
The method above is completely FP, but it cannot be used in a pure FP context when using Java. This should be placed inside the C
class in Java and can only be called after you have created an instance of this type of object. This last part will disqualify the Java C
class from FP, but the method will still be.
Edit: in fact, you can have static methods in Java that you can use without any instantiation. Therefore, if you change the signature to static int fib (int x)
, then the method and method calls can still be FP if they are called in an FP manner.
Re: your comment
The recursion can be FP, but it does not have to be (see below):
def f(first, rest): print first first = rest[0]; rest = rest[1:] f(first, rest)
You can also have FP without recursion:
def sum (a,b): return a+b def square(c): return c*c def square_of_sum (x,y): return square(sum(x,y))