adamreeve / semver.net

Semantic versioning for .NET
MIT License
117 stars 22 forks source link

Consider adding the generic IComparable interface to Version to simplify F# usage. #42

Closed atlemann closed 5 years ago

atlemann commented 5 years ago

In F#, comparison operations such as sorting expects the generic IComparable interface and not IComparable<T>. To sort by SemVer in F# you'd have to do something like this:

Wrap Version in a thing implementing IComparable:

[<CustomEquality;CustomComparison>]
type ComparableVersion =
    { Version : Version }
    static member create version =
        { Version = version }

    override x.Equals(yObj) =
        match yObj with
        | :? ComparableVersion as y -> x.Version.Equals(y.Version)
        | _ -> invalidArg "yObj" "Type must be a ComparableVersion"

    override x.GetHashCode() = x.Version.GetHashCode() 

    interface System.IComparable with
        member x.CompareTo yObj =
            match yObj with
            | :? ComparableVersion as y -> x.Version.CompareTo(y.Version)
            | _ -> invalidArg "yObj" "Type must be a ComparableVersion"

Then you can sortBy like this:

|> Seq.sortBy (fun v -> Version(Path.GetFileNameWithoutExtension f) |> ComparableVersion.create)
adamreeve commented 5 years ago

Hi @atlemann, I'd be happy to accept a PR for this change but don't have much time to do it myself.

Thanks, Adam

atlemann commented 5 years ago

@adamreeve Done! :)