1

For me, the natural meaning of the function Part is "get the sub-expression at appointing position." It is quite unlike Take, Take always keeps the head in the process. For example, by using Take:

Take[f[a, b, c[i], d[j, k], e, f], {3, 4}, 1]
(* Take the third to fourth position at level 1; and first position at level 2 *)
(* Output: f[c[i], d[j]] *)

When using Part:

Part[f[a, b, c[i], d[j, k], e, f], 4, 2]
(*Take the expression directly at the position 4, 2*)
(* Output: k *)

Until now, the mechanism of both functions is quite natural to me. However, the next result leaves me feeling confused:

f[a, b, c[i], d[j, k], e, f][[4]]
f[a, b, c[i],d[j, k], e, f][[4;;5]]

The output is d[j, k] versus f[d[j, k], e]. I don't know why I get the latter result -- where the extracted parts are wrapped with f. I was expecting {d[j, k], e}.

Is this design reasonable or useful in most cases? What is its intended use?

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Eric
  • 1,191
  • 7
  • 20
  • It is documented in ref/ Part details section. And it can be useful Hold[Print[1], Print[2]][[{1}]] – Kuba Feb 21 '18 at 14:09
  • @Kuba I just found that the usage of Part[expr,{n}] seems undocumented. – Eric Feb 21 '18 at 14:18
  • 1
    How is that undocumented? Isn't it the 4th usage? And see also the 4th bullet point in Details section. – Kuba Feb 21 '18 at 14:19
  • Ya, but the document said "gives a "list" of the parts $i_1,~i_2,~\cdots$ of expr." According to it, the result should be surrounded by the {}(namely, a list) right? – Eric Feb 21 '18 at 14:24
  • Oh I see. In the Details, they said more. – Eric Feb 21 '18 at 14:27
  • It might be worth comparing with Extract[f[a, b, c[i], d[j, k], e, f], {{4}, {5}}]. – Michael E2 Feb 21 '18 at 15:07
  • As far as I always understood, things like Part[expr, Span[__]] and Part[expr, All] are basically syntactic sugar for invoking Take. – Sjoerd Smit Feb 21 '18 at 15:23
  • @SjoerdSmit Do you prefer using Take instead of Part[expr, List[__]]? – Eric Feb 21 '18 at 15:26
  • 1
    This and this QAs seem relevant, if not duplicates. – Leonid Shifrin Feb 21 '18 at 19:08
  • @Eric Well, Part[expr, List[__]] is something you can't really do with Take. For example, there's no way to do f[a,b,c,d,e][[{1, 2, 5}]] with Take. As for personal preference: I actually prefer to stick with Part most of the time, except when I need Take[list, UpTo[n]] (which actually works with Part and Span as well, but is rather ugly). – Sjoerd Smit Feb 23 '18 at 10:39

0 Answers0