Search code examples
python-3.xfunctional-programmingfunctional-dependenciesfunctional-interfacepurely-functional

Is there a solution for the match-mapping-group pattern in python by Functional programming?


For example, I have a list such as [2, 4, 7, 9, 6, 12, 38]. I want to firstly recognize each number by whether it is odd, then add 100 to each odd and 101 to each even,finally get two lists. There are 3 steps: 1. Number matching that it is odd or even 2. Add a proper decimal to each odd and even 3. Group to two list

In python, might need 3 minimal functions, but still how should we reach the goal by using Functional programming?


Solution

  • The order of the steps seems forced and makes functional programming a lot harder, so with an open order a Python implementation would be the following:

    odd = lambda x: x % 2 == 1
    even = lambda x: not odd(x)
    l = [2, 4, 7 ,9 ,36]
    listodd = [i + 100 for i in l if odd(i)]
    listeven = [i + 101 for i in l if no odd(i)]
    

    So every list is created with one expression, and list comprehensions are definitely valid functional programming. Another way to express the list comprehension would be with filter and map:

    listodd = map(filter(l, odd), lambda x: x + 100)
    listeven = map(filter(l, even), lambda x: x + 101)
    

    The code is still highly redundant, but as for now I have no idea how to write this shorter and cleaner.