1
votes

I came across the question Python - Removing duplicates in list only by using filter and lambda, where the OP asks how to remove duplicate elements from a Python list using exclusively filter and lambda functions.

This made me wonder, is it possible, from a theoretical point of view, to remove the duplicates from a Python list using only lambda functions?

If so, how can we do that?

In this case, "removinge the duplicates" means "keeping exactly one occurrence of each element present in the original list", so [1,2,1,3,1,4] should become [1,2,3,4].

In addition, the goal is to write only one lambda, so the code would be a one-liner like:

lambda l: """do something that returns l without duplicates"""

No external variable must be used.

Besides, as for the above question, nothing "fancy" is allowed, especially the set function, as well as reduce, map...

Basically, no other function, even the built-in, should be called.

1
lambda functions only and no temporary placeholders/containers?wwii
@wwii Edited my question; yes, the code must exclusively consist in one lambda function, so no additional container is allowed.Right leg
Sometimes it is a bit tricky but generally you can find a way to write a lambda version of a function regardless of how messy or unreadable it may be.wwii
@wwii Check my answer to see how messy it is :)Right leg
lambda a: list(set(a))??wwii

1 Answers

4
votes

From a theoritecal point of view, if a computational problem requires an input and an output without side-effect, lambda calculus can probably solve it (more generally, lambda calculus is Turing complete, cf wikipedia).

Now for the implementation, the following lambda function takes a list argument, and returns a list where all the duplicates have been removed:

lambda l: (lambda u, a: u(u, a)) ((lambda f, x: x if len(x) <= 0 else (f(f, x[1:]) if x[0] in x[1:] else ([x[0]] + f(f, x[1:])))), l)

Here is an unwrapped version:

lambda l:
    (lambda u, a: u(u, a))
    (
        (lambda f, x: x if len(x) <= 0
                        else
                        (
                            f(f, x[1:]) if x[0] in x[1:]
                                        else ([x[0]] + f(f, x[1:]))
                        )
         ),
         l
    )

The function consists in a lambda version of the following recursive function:

def f(l):
    if len(l) <= 0:
        return l
    elif l[0] in l[1:]:
        return f(l[1:])
    else:
        return ([l[0]] + f(l[1:]))

To emulate a recursive call, the equivalent lambda takes an additional function as argument, that will be itself:

lambda f, x: x if len(x) <= 0
               else
               (
                   f(f, x[1:]) if x[0] in x[1:]
                               else ([x[0]] + f(f, x[1:]))
               )

Then, another lambda calls this previous function, passing itself as argument (besides the list):

lambda u, a: u(u, a)

Finally, an outer lambda wraps everything up, that takes only a list as argument.