0
$\begingroup$

I would like a function f, that takes as input a list, not care about the order of elements of the list. So,for example:

f[{3,2}]=f[{2,3}]

Is this possible? Or is it necessary to convert the list into a set? If so how can I the conversion be done?

Thank you in advance

$\endgroup$
  • $\begingroup$ It is not clear what you mean. Please give an example of what such a function should do with f[{x,y}]. $\endgroup$ – Somos Sep 2 at 23:49
2
$\begingroup$

You can also use OrderlessPatternSequence:

ClearAll[f1]
f1[{OrderlessPatternSequence[x_, y_, z_]}] := {{{x}, {z}, {y}}}

f1[{2, 3, 1}]

{{{1}, {3}, {2}}}

f1[{3, 2, 1}]

{{{1}, {3}, {2}}}

You can use it with a subset of arguments:

ClearAll[f2]
f2[arg1_, OrderlessPatternSequence[x_, y_, z_], arg2_List] := {x, y, z, arg1, arg2}

f2[t, 2, 1, 3, {x}]

{1, 2, 3, t, {x}}

f2[t, 1, 2, 3, {x}]

{1, 2, 3, t, {x}}

$\endgroup$
1
$\begingroup$

I'm guessing that you want to compare lists for equality using == (not =), but ignoring order. There are many ways. One way is to make a new kind of list wrapper:

SetAttributes[orderlessList, Orderless]

You need not define any values for orderlessList: it's just a wrapper. Now, a conversion from List to orderlessList:

orderless[x_List] := Apply[orderlessList, x]

Then,

orderless[{3, 2}] == orderless[{2, 3}]
(* True *)
$\endgroup$

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.