F# Scribbles

My experiments with F#

Python Numpy array.argsort() in F#

In Python Numpy, the array.argsort returns the indices that would sort an array.

For example,

1
2
k = array ([1, 5, 3, 7, 2])
k.argsort()

will give

1
array([0, 4, 2, 1, 3])

In F# we can do that as depicted below.

Let there is an array

1
let k = [| 1; 5; 3; 7; 2 |]

To get argsort as like above

1
2
3
4
k
|> Array.mapi (fun index value -> (value, index))
|> Array.sort
|> Array.map (fun v -> snd v);;

Array.mapi helps to return a tuple with first element as array value and second element as index position. This array has been sorted by the first element. Finally Array.map helps to return second element of the tuple. The result is

1
val it : int [] = [|0; 4; 2; 1; 3|]