Python: List Comprehension and Functional Programming

Question:

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)

Asked By: hqt

||

Answers:

I’m sure that others will be able to explain it better than I will but functional programming just has mostly to do with how you think of the flow of the program and whether or not you can pass around functions as objects to compute on. For example in javascript when you provide a function to be executed when an even fires this is passing around a function and in this sense it is almost like functional programming.

This is the sense in which list comprehension is like functional programming because you are giving instructions on how to compute each element rather than the more procedural approach which would be to loop through and do the computation yourself rather than hand it off as a function. Python isn’t really what I would consider a true functional-programming language like LISP or ML or Haskell, (is erlang? can’t remember) but it can do somethings like it (look into lambda expressions in python).

Java and C/C++ are not really functional either but you could simulate it with function pointers as arguments. Not that familiar with C#…

Event driven languages tend to make use of this idea of function passing more just because they need some way to pass unknown code to be executed at a later date.

Answered By: hackartist

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

Answered By: Harald Brinkhof

Simple i think
The terms Map and Reduce come from Lisp and functional programming.

and python has

filter,map and reduce

ref :http://www.joelonsoftware.com/items/2006/08/01.html

 http://docs.python.org/tutorial/datastructures.html
Answered By: dilip kumbham

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.

Answered By: beoliver

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))
Answered By: Arnab Datta