# 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

• Commented Sep 26, 2018 at 17:30
• The help page for Reap[] features one of the older solutions. Commented 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. Commented 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. Commented Sep 26, 2018 at 17:38
• @Mateus No, DeleteRepeated is not a built-in function, the built-in function is called DeleteDuplicates. Commented Sep 26, 2018 at 17:39
• You are right. I'm sorry. Commented 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)` Commented Sep 26, 2018 at 18:44