Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python and functional programming: is there an apply() function?

Scala has the apply() function.

I am new to Python and I am wondering how should I write the following one-liner:

(part_a, part_b) = (lambda x: re.search(r"(\w+)_(\d+)", x).groups())(input_string)

I would feel better with something like:

(part_a, part_b) = input_string.apply(lambda x: re.search(r"(\w+)_(\d+)", x).groups())

Am I wrong from a FF viewpoint? Is there such construction in Python?

Edit: I know about the poorly picked snippet.

like image 893
Benoit Avatar asked Aug 27 '15 12:08

Benoit


3 Answers

When writing Haskell write Haskell. When writing Python just write Python:

part_a, part_b = re.search(r"(\w+)_(\d+)", input_string).groups()
like image 111
scytale Avatar answered Oct 18 '22 01:10

scytale


If you're using a Python without apply, you could always write it yourself...

def apply(fn, args=(), kwargs=None):
    if kwargs is None:
        kwargs = {}
    return fn(*args, **kwargs)

just because you could, doesn't mean you should..

like image 23
thebjorn Avatar answered Oct 18 '22 03:10

thebjorn


Python does not have such a construct; what would be the point? lambda x: ... is a function, and therefore it should be used like a normal function, i.e., as (lambda x: ...)(input_string) as in your first snippet.

However, in your case, I see no reason why you should even bother with a lambda; just do:

(part_a, part_b) = re.search(r"(\w+)_(\d+)", input_string).groups()
like image 39
jwodder Avatar answered Oct 18 '22 01:10

jwodder