# How to create a function that eliminates repeated elements

I want to create a function that eliminates repeated elements from a list without changing the order.

For example:

DeleteRepeated[{a, b, 5, a, x + y, a + b, x + y, 7, 5}]


should return:

{a, b, 5, x + y, a + b, 7}


How can I do that in a recursive way? I want to use less then possible the functions done from Mathematica.

PS: It is just for exercise

• Sep 26, 2018 at 17:30
• The help page for Reap[] features one of the older solutions. Sep 26, 2018 at 17:45
• This old MathGroup post (from 2000), as well as the discussion on Union without sorting by Ted Ersek (under 'Clever Little Programs'), may be of interest. Sep 26, 2018 at 19:33

You can use my very old solution for this:

f[x_] := (f[x]=Sequence[]; x)

DeleteRepeated[list_] := InternalInheritedBlock[{f},
f /@ list
]


Then:

DeleteRepeated[{a, b, 5, a, x + y, a + b, x + y, 7, 5}]


{a, b, 5, x + y, a + b, 7}

• DeleteRepeated is a function already done from Mathematica. I want to avoid this. Sep 26, 2018 at 17:38
• @Mateus No, DeleteRepeated is not a built-in function, the built-in function is called DeleteDuplicates. Sep 26, 2018 at 17:39
• You are right. I'm sorry. Sep 26, 2018 at 17:43
• @Carl Woll In 2015, Version 10.2 introduced Nothing. That was after your 'very old' and clever solution. Using Nothing: f[x_] := (f[x] = Nothing; x)` Sep 26, 2018 at 18:44