Unsort: remembering a permutation and undoing it

后端 未结 3 948
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-06 02:11

Suppose I have a function f that takes a vector v and returns a new vector with the elements transformed in some way. It does that by calling function g that assumes the vec

3条回答
  •  无人及你
    2021-01-06 02:27

    Here's a "sorting wrapper" pattern suggested by Michael Pilat earlier

    Clear[g];
    g[a_] := If[OrderedQ[a], a^2, Print["Failed"]];
    g[{3, 2, 1}]
    g[a_] := g[Sort@a][[Ordering@Ordering@a]] /; Not[OrderedQ[a]];
    g[{3, 2, 1}]
    

提交回复
热议问题