Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: List Comprehension and Functional Programming

In my Python learning book, when I read about List Comprehension, the author has a small note explaining:

Python’s list comprehension is an example of the language’s support for functional programming concepts.

I have go on wikipedia to read about functional programming. But I hard to imagine because I don't see any connection between List Comprehension and this concept in as explained wiki page.

Please give me a clear explanation (and if can, give me some more examples about functional programming in Java or C# too :D)

like image 511
hqt Avatar asked Jun 09 '12 10:06

hqt


People also ask

Can you use Python for functional programming?

Many programming languages support some degree of functional programming. In some languages, virtually all code follows the functional paradigm. Haskell is one such example. Python, by contrast, does support functional programming but contains features of other programming models as well.

What is list comprehension function in Python?

A Python list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list. Python List comprehension provides a much more short syntax for creating a new list based on the values of an existing list.

Is list comprehension a built in function?

In this lesson, you'll learn how to use list comprehensions to construct various lists, and different list methods to manipulate lists. They're used in place of functions like map() and filter() . To learn more, check out Using List Comprehensions Effectively.

Are list comprehensions good practice?

List comprehensions are great because they require less lines of code, are easier to comprehend, and are generally faster than a for loop. While list comprehensions are not the most difficult concept to grasp, it can definitely seem unintuitive at first (it certainly was for me!).


3 Answers

If your question is "give me some examples that show how FP works in python", then :

What is pure Functional Programming (in Python)?

It is a programming paradigm that avoids state and mutable data and instead relies on function return values. This means a purely functional program written in python will not have things like variables, states etc.

Not so pure FP

You can combine the FP and imperative paradigm, and with good results (see here). The linked gist is a math quiz program I made for a python class I took some 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 pure 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 needs to be put inside of a class C in Java, and can only be called after you have instantiated an object of that type. This last part disqualifies the Java class C from being FP, but the method will still be.

Edit : actually, you can have static methods in Java which can be used without any instantiation. So if you change the signature to static int fib (int x) , then the method and it's method calls might still be FP if called in a FP-manner.


Re : your comment

Recursion may 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))
like image 177
Arnab Datta Avatar answered Nov 08 '22 10:11

Arnab Datta


Python's map(), reduce() and filter() take a sequence, apply another function of your choice to it and then return a different sequence to you, leaving the original sequence intact.

You could say that that's functional since it doesn't touch the original sequence, doesn't touch its state internally and doesn't produce side-effects. (though the function you yourself provide to it could do some of the above, like produce a side-effect)

Functional Programming is a different way of programming and structuring your application to reduce errors caused by side-effects (changing some value in another static location or process directly) and to reduce or eliminate the need to synchronize access to shared data. Some languages force you into this, like erlang and others leave it more up to you to choose which path suits you best at the time (procedural or functional), with preference to the functional side of the programming spectrum, like scala

like image 38
Harald Brinkhof Avatar answered Nov 08 '22 11:11

Harald Brinkhof


I believe Pythons List comprehensions are taken directly from Haskell (a very 'pure' functional language).

Haskell:

[ x | x <- [1..10] ]

Python:

[ x for x in range(1,11) ]

as people have mentioned, Python does allow functional concepts, such as map(), reduce(), and lambda

while these are all functional ideas, they can seldom be used in a purely functional way as Python is not recursion friendly.

if you want to find out about "Functional" languages look into 'Haskell', 'Scala', 'Clojure', 'Erlang', 'F#' ... which are all more or less functional (although some might suggest that is not the case)

And If you really want to understand what functional programming is about have a look here. learn you a haskell for great good which is easy reading, has nice pictures and will open your eyes.

EDIT -

Examples of Haskell factorial functions (all do the same thing):

fact1 0 = 1
fact1 n = n * fact1 (n - 1)


fact2 n | n == 0 = 1
        | otherwise = n * fact2 (n - 1)


fact3 n = case n of
            0 -> 1
            _ -> n * fact3 (n - 1)

ps, have a look at this question as well as it is relevant.

like image 4
beoliver Avatar answered Nov 08 '22 10:11

beoliver