Abion47 / darq

A port of .NET's LINQ IEnumerable functions to Dart.
MIT License
85 stars 9 forks source link

Sorting does not work correctly for lists with nullable types #15

Closed Tropid closed 2 years ago

Tropid commented 2 years ago

It seems like sorting a list of nullable types does not work.

Minimal example:

pubspec.yaml

name: sorttest
description: A simple command-line application.
version: 1.0.0

environment:
  sdk: '>=2.14.4 <3.0.0'

dependencies:
  darq: ^1.1.1

bin/main.dart

import 'package:darq/darq.dart';

void main() {
  final xs = <int?>[null, 1, 3, 2, null];
  print(xs.orderByDescending((x) => x));
}

Expected output:

Either (null, null, 3, 2, 1) or (3, 2, 1, null, null).

Actual output:

(null, 1, 3, 2, null)

Dart version:

Dart SDK version: 2.14.4 (stable) (Wed Oct 13 11:11:32 2021 +0200) on "linux_x64"

Darq version (from lockfile):

darq:
    dependency: "direct main"
    description:
      name: darq
      url: "https://pub.dartlang.org"
    source: hosted
    version: "1.1.1"
Abion47 commented 2 years ago

There is no well-defined ordering behavior for null I can find that would form the basis of the assumption that it should come at the beginning or at the end of an ordered set. Some sources I see will put it at either the beginning or the end of a list purely as an implementation detail, while others will leave it as undefined behavior or even an error.

As such, it's unclear which behavior to adopt for this package, so I will adopt the "undefined behavior" strategy and leave it up to users to define their own ordering functions with the desired behavior.