I don't understand behavior of distinctBy in this snippet:
let s = [123; 231; 321]
let s1 = s |> Seq.map (string >> Seq.sort)
let s2 = s |> Seq.distinctBy (string >> Seq.sort)
which produces:
s1 = seq [seq ['1'; '2'; '3']; seq ['1'; '2'; '3']; seq ['1'; '2'; '3']]
as expected, but:
s2 = seq [123; 231; 321]
where I expected only one element, because the 3 keys are identical. Which part I got wrong?
F# does not compare Sequences for equality see this example
(123 |> string |> Seq.sort) = (123 |> string |> Seq.sort)
val it : bool = false
I imagine this is to allow support for infinite sequences.
You can fix this by mapping to lists
let s = [123; 231; 321] |> Seq.distinctBy (string >> Seq.sort >> Seq.toList);;
val s : seq<int>
> s;;
val it : seq<int> = seq [123]
Seq.sort probably doesn't implement comparison logic. So the underlying implementation sees three distinct objects.
Similar if you did the following:
object.ReferenceEquals("1", 1.ToString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With