• entries
73
131
• views
54722

# Python #6 - A functional language?

110 views

It's obvious that whoever designed Python liked functional languages.

Well, at least liked some of its features. Functional languages like ML and Lisp are really cool because of what can be done in small lines of code. However, I don't think I could seriously program in a functional language... I like imperative statements. But what if I want some of the functional languages' features?

I'd use Python! It's an imperative language that has a lot of similarities with functional languages, even with the fundamental design difference. I've said this before when I mentioned anonymous functions and other things. Now check this out.

Python has three cool functions: filter, map, and reduce. These functions work with sequences and apply a user-defined function to each element of the sequence. Say we have a sequence S and a user-defined function F. Filter returns a sequence that contains all the elements to which F(S) is true. Map simply applies F to each element in S; you can also pass multiple sequences if your function takes multiple arguments and it binds an element with the same index from each sequence as each parameter. Reduce applies the function to the first two elements, and then each element and combines it into a single value. Anyway, I didn't want to go into too much detail about this, but it's a very cool feature.

Python even takes this further with something call "list comprehensions." You can construct a list from another list by defining an operation to be done on each element of the list; you can also include a conditional clause to restrict the list. There's really no way to explain this besides showing examples:
>>> myChar = ['a', 'b', 'c']>>> [3*c for c in myChar]['aaa', 'bbb', 'ccc']>>> [3*c for c in myChar if c < 'b']['aaa']>>> [[c, c+'1'] for c in myChar][['a', 'a1'], ['b', 'b1'], ['c', 'c1']]

That's freaking awesome.

## 1 Comment

I agree. I love Lisp. I really love how Python is so interoperable and fleshed out.

## Create an account

Register a new account