2
$\begingroup$

I have the following line code:

Cases[g[h, r, t, b, m], x_[__, y_, __] -> y, {0, -1}]

I am expecting the results to be {r,t,b} because they match the pattern, but I am only getting {r}.

Can anyone suggest why I am getting only {r}?

$\endgroup$

3 Answers 3

8
$\begingroup$

If your aim is to remove the first and last argument:

Cases[g[h, r, t, b, m], _[_, y__, _] :> y, {0}]

Don't forget to localize y with :>

g[h, r, t, b, m][[2 ;; -2]] /. g -> List

List @@ (g[h, r, t, b, m][[2 ;; -2]])

Delete[List @@ fun, {{1}, {-1}}]
$\endgroup$
3
  • $\begingroup$ +1, but I don't think :> is necessary? $\endgroup$
    – mfvonh
    Jul 13, 2014 at 21:22
  • $\begingroup$ @mfvonh It is necessary. Without it, if y has a global value it will be used rather than the sequence matching the pattern y__. $\endgroup$
    – Mr.Wizard
    Jul 13, 2014 at 22:45
  • $\begingroup$ @Mr.Wizard Oh oops, duh. $\endgroup$
    – mfvonh
    Jul 13, 2014 at 22:47
5
$\begingroup$

Try using Longest:

Cases[g[h, r, t, b, m], x_[__, Longest@y__, __] -> y, {0}]

Your single underscore after y only matches 1 element.

$\endgroup$
0
$\begingroup$
ReplaceList[g[h, r, t, b, m], _[__, y_, __] :> y]
(*{r, t, b}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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