Home > other >  Why does Dart typing system make equate difficult and does that bar pattern matching?
Why does Dart typing system make equate difficult and does that bar pattern matching?

Time:11-01

I tried to do this thing in dart but it failed and I don't really understand why. I know that dart doesn't support robust "Pattern Matching" like elixir does, but I thought it should be able to compare two lists. No. Why not? what is it about the typing system that can't equate two lists and if it could, could it support even rudimentary pattern matching? I'm just trying to understand how equate works in dart I guess.

void main() {
  final x = 1;
  final y = 2;
  if (x == 1 && y == 2) {
    print('this works fine of course');
  }
  
  if ([1, 2] == [1, 2]) {
    print('but this does not');
  }

  if ([x, y] == [1, 2]) {
    print('would this work if dart could equate lists?');
  }
}

CodePudding user response:

Dart lists do not implement operator== in a way that checks the elements for equality. Dart lists are assumed to be mutable, and the Dart platform libraries generally do not provide an equality for mutable objects, because they are not guaranteed to preserve that equality over time. Also, for lists, because it's not obvious which equality to use. Should it just compare elements? Then a <num>[1] list would be equal to <int>[1], even if they are very different lists.

For those reasons, you are supposed to decide which equality you actually want, without one being the canonical one.

You can, for example, use const ListEquality().equals from package:collection. It defaults to using == on the elements, but can be configured to use other equalities as well.

CodePudding user response:

import 'package:flutter/foundation.dart';

void main() async {
 final x = 1;
 final y = 2;
 if (x == 1 && y == 2) {
   print('this works fine of course');
 }

 if (listEquals([1, 2],[1, 2])) {
   print('Yep');
 }

 if (listEquals([x, y], [1, 2])) {
   print('would this work if dart could equate lists? Yep');
 }
}

Output:

 this works fine of course
 Yep
 would this work if dart could equate lists? Yep
  • Related