Jump to content
  • Advertisement
Sign in to follow this  
  • entries
  • comments
  • views

Python #6 - A functional language?

Sign in to follow this  


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']
>>> [[c, c+'1'] for c in myChar]
[['a', 'a1'], ['b', 'b1'], ['c', 'c1']]

That's freaking awesome.

Sign in to follow this  

1 Comment

Recommended Comments

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

Share this comment

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!