F # & # 8594; Seq to map

I try to load all my Categories from a database and then map them to Map (dictionary?), However, when I use the following code:

 [<StructuralComparison>] type Category = { mutable Id: string; Name: string; SavePath: string; Tags: ResizeArray<Tag> } let categories = session.Query<Category>() |> Seq.map(fun z -> (z,0)) |> Map.ofSeq 

it just gives an error message:

The Category, Record, or Union type "Category" has the "Structural Compatibility" attribute, but the type of the "ResizeArray" component does not satisfy the "comparison" constraint

I have absolutely no information on what to do, so any help is appreciated!

+4
source share
2 answers

F # rightly complains that ResizeArray<_> does not support structural comparison. ResizeArray<_> instances are mutable and do not support structural comparison, so you cannot use them as record fields that are used as keys to Map<_,_> (which are sorted by key). You have several options:

  • Use Tags a collection type that supports structural comparison (for example, an immutable Tag list ).

  • Use [<CustomComparison>] instead of [<StructuralComparison>] , which requires the implementation of IComparable .

  • Use a mutable dictionary (or other appropriate collection type) instead of Map . Try using dict instead of Map.ofSeq , for example.

+5
source

The problem is that by adding the StructuralComparison attribute to the Category type, you asked F # to use structural comparison when comparing Category instances. In short, it will compare each item separately to make sure they are equal, to determine if two instances of Category are equal.

This puts an implicit restriction on each Category member for itself comparable. The ResizeArray<Tag> generates an error because it is not comparable. This is true for most types of collections.

To get rid of this error, you need to map the ResizeArray<T> or select a different key for Map . Don has a great blog entry that delves into this topic and offers several different ways to achieve this. It is very important to read

+5
source

Source: https://habr.com/ru/post/1346611/


All Articles