1
$\begingroup$

I want to delete the f[g[...]] last appear in a iterative list.Such as:

{f[1], g[2], {3, f[g[5]], {1, f[g[5]], f[g[8]]}, 1}, 
 f[g[9]], 6, {f[9], {g[5], f[g[6]]}}, {f[f[6]], f[g[6]], 8}, f[3]}

I want to delete the last f[g[6]] but don't change the list structure to get

{f[1], g[2], {3, f[g[5]], {1, f[g[5]], f[g[8]]}, 1}, 
 f[g[9]], 6, {f[9], {g[5], f[g[6]]}}, {f[f[6]], 8}, f[3]}

How to do this?

$\endgroup$
3
$\begingroup$

You could use Position to find the pattern, take the last one, and set it to nothing. As a function:

ClearAll@lastfg;
lastfg[list_] := Module[{temp = list},
  (temp[[##]] = Sequence[]) & @@ Last@Position[temp, f[g[_]]];
  temp]
$\endgroup$
2
  • $\begingroup$ Cases or DeleteCases can do this? $\endgroup$
    – yode
    Oct 25 '16 at 0:28
  • $\begingroup$ @yode The trouble with Cases is that you have no idea which is the last occurance, so you can't pick just that one. (Unless you want to run it twice with some silly counting thing the second time). With DeleteCases you can specify you want to delete the first $n$. Unfortunately you can't put in a negative number to delete the last $n$. $\endgroup$
    – wxffles
    Oct 25 '16 at 1:52

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.