Choub890
Choub890

Reputation: 1163

Sorting an Array so that all elements with Some are in front

I have an F# record type (Request<'a>) defined with one of its field as an ('a -> bool) option. At some point, I have an array of this record type, and would like to have it sorted so that all of the ones with Some ('a -> bool) would be first (lowest index), and all the ones with None would be last (highest index).

I have tried doing the following, but this does not seem to work as I have some of them that are in the middle/end of the array:

let sort (req1:Request<'a>) (req2:Request<'a>) =
    if req1.ResourceCondition.IsSome
    then
        -1
    else if req2.ResourceCondition.IsSome
    then
        1
    else
        0

let reqArray = Array.sortWith sort fifoArray

Upvotes: 1

Views: 86

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

Your comparing function has flawed logic. Try to run it step by step. Look: if both req1 and req2 are Some, then your function will return -1. Not what you'd expect, is it?

I would rather express it in terms of pattern matching:

let sort (req1:Request<_>) (req2:Request<_>) =
    match req1.ResourceCondition, req2.ResourceCondition with
    | None, Some _ -> 1
    | Some _, None -> -1
    | _ -> 0

Upvotes: 11

Related Questions