1
votes

Below is a working samle of Array.sub in F#

let a1 = [| 0 .. 99 |]
let a2 = Array.sub a1 5 10
printfn "%A" a2

I tried using the pipeline operator |> by neither this code worked with me:

a1 |> Array.sub 5 10

Neither this:

a1 5 10 ||> Array.sub

Is there a possible way?!

2

2 Answers

4
votes

The operator |> sends the last argument of the function.

So it will be:

10 |> Array.sub a1 5

In the other case, it's the last 2 arguments, but they should be sent in a tuple:

(5, 10) ||> Array.sub a1 

Here's another option which might be closer to what you're looking for:

a1 |> Array.sub <|| (5, 10)
4
votes

I suspect that the Array.sub function has this order of arguments for compatibility reasons. The order is the same in OCaml version which is what F# started with a long time ago. This is a bit unfortunate, because it means that the function is not very well suited for piping.

I would probably define a new function that just reverses the order of arguments. Note that you can define your own Array module and so you'll see it along with all other array functions:

module Array = 
  let subArray lo hi arr = Array.sub arr lo hi

Now you can use Array.subArray in a pipeline without using other pipeline-like operators that (in my humble opinion) make code much harder to read:

let something = 
  [| 0 .. 99 |]
  |> Array.map (fun x -> x * 2)
  |> Array.subArray 5 10