# How to make an operator form of Part[] to use with // (Postfix)

I've often found myself chaining multiple functions in Mathematica using the // postfix form, and then needing to extract specific parts of the result. The standard approach involves using parentheses and [[]] notation, which can make the code less readable. Additionally, I often don't plan ahead and include the parentheses from the beginning, requiring me to go back and wrap them, which is annoying.

For example, consider the following sequence of function applications:

expr = Range[10];
result = (expr // ftn1 // ftn2 // ftn3)[[2 ;; 5]]


I think sometimes that can be both less readable, and more tedious if you have to retroactively put in the parentheses. I would very much like a operator form of Part that I can add to the chain.

result = expr // ftn1 // ftn2 // ftn3//part[2;;5]


Can we do this in a concise enough syntax to be worth it while keeping all the power of using ;; aka Span?

I searched for duplicates but did not see any, feel free to close this question if I missed anything.

• One alternative to putting in the parentheses is, for example, Range[10] // #[[3;;5]]&. Arguably, it is unreadable, but it does not require searching for matching parentheses or defining a new function. Commented 2 days ago

Yes, this is actually surprisingly easy! We simply do the most obvious thing.

part[spec_] := Part[#, spec] &


This works as desired, for example

ftn1[x_] := x^2
ftn2[x_] := x + 1
ftn3[x_] := Sqrt[x]
expr = Range[10];
result = expr // ftn1 // ftn2 // ftn3 // part[2 ;; 5]
(*Expected output:{Sqrt[5],Sqrt[10],Sqrt[17],Sqrt[26]}*)


Additionally, it works for all versions of ;; i.e. Span:

(*Test cases for each Span definition*)

test1 = arr // part[2 ;; 5] (*Expected:{2,3,4,5}*)
test2 = arr // part[6 ;;] (*Expected:{6,7,8,9,10}*)
test3 = arr // part[;; 4] (*Expected:{1,2,3,4}*)
test4 = arr // part[ ;; ] (*Expected:{1,2,3,4,5,6,7,8,9,10}*)
test5 = arr // part[2 ;; 8 ;; 2] (*Expected:{2,4,6,8}*)
test6 = arr // part[3 ;; ;; 3] (*Expected:{3,6,9}*)
test7 = arr // part[;; 7 ;; 2] (*Expected:{1,3,5,7}*)
test8 = arr // part[;; ;; 4] (*Expected:{1,5,9}*)


and it precedence is convenient for using Map infix form /@

f /@ {1, 2, 3} // part[1 ;; 2] (*expected output: {f[1],f[2]}*)


I'm using version 14.0

Query can be used for this:

Range[10] // Query[2 ;; 5]


Note that Query behaves slightly different for non-existing elements:

Range[10] // Query[5 ;; 12]
Range[10] // Query[12]


{5, 6, 7, 8, 9, 10}

Missing["PartAbsent", 12]

If you like a more functional approach, there is OperatorApplied.

part = OperatorApplied[Part];

{a, b, c, d} // part[4]
(* d *)

{a, b, c, d} // part[2 ;; 3]
(* b, c *)