3
$\begingroup$

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

$\endgroup$
3

1 Answer 1

2
$\begingroup$

You can use my very old solution for this:

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

DeleteRepeated[list_] := Internal`InheritedBlock[{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}

$\endgroup$
4
  • $\begingroup$ DeleteRepeated is a function already done from Mathematica. I want to avoid this. $\endgroup$
    – Mateus
    Sep 26, 2018 at 17:38
  • 2
    $\begingroup$ @Mateus No, DeleteRepeated is not a built-in function, the built-in function is called DeleteDuplicates. $\endgroup$
    – Carl Woll
    Sep 26, 2018 at 17:39
  • $\begingroup$ You are right. I'm sorry. $\endgroup$
    – Mateus
    Sep 26, 2018 at 17:43
  • 1
    $\begingroup$ @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) $\endgroup$ Sep 26, 2018 at 18:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.