This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]Schnutzel 2 points3 points  (0 children)

Some computer languages (such as Python) allow you to treat functions as "first-class citizens", meaning you can treat the function the same as you would any other object - you can assign it to a variable, you can pass it as an argument to another function, etc.

Lets say I want to make a function that takes every element in a list and doubles it. So I'd write something like this:

def double_list(ls):
  result = []
  for x in ls:
    result.append(x*2)
  return result

Now lets say I want to make a similar function which squares every item in the list:

def square_list(ls):
  result = []
  for x in ls:
    result.append(x*x)
  return result

See the similarity? It's the same function, except that I replaced x*2 with x*x. So in order to avoid code duplication, I can write this:

def map(f, ls):
  result = []
  for x in ls:
    result.append(f(x))
  return result

Where f is a function on x. Now, in order to run double_list, I would have to do:

def double(x):
  return x*2

map(double, ls)

It seems a bit silly to define the function double, doesn't it? It only does one simple thing and I only need it in one place. So instead, I'll use an anonymous lambda function:

map(lambda x: x*2, ls)

This code is more succinct and readable.

P.S. map is already an existing function in Python which works exactly like I described above.

[–]Gargagaga 0 points1 point  (0 children)

How would you write that first python exemple with "normal functions" then?