Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# distinctBy behavior

Tags:

identity

f#

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?

like image 739
Paul Jurczak Avatar asked May 10 '26 10:05

Paul Jurczak


2 Answers

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]
like image 122
John Palmer Avatar answered May 13 '26 11:05

John Palmer


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());
like image 23
Guvante Avatar answered May 13 '26 13:05

Guvante



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!