Steven Proctor posted an example of Ruby's Enumerable#group_by
:
["tar", "rat", "bar", "rob", "art", "orb"].group_by {|word| word.chars.sort}
# => {["a", "r", "t"]=>["tar", "rat", "art"],
# ["a", "b", "r"]=>["bar"],
# ["b", "o", "r"]=>["rob", "orb"]}
I decided to do the same thing in F#:
let grouped = seq ["tar";"rat";"bar";"rob";"art";"orb"]
|> Seq.groupBy (fun word -> word |> Seq.sort)
... but I did not get the same results as the Ruby program:
seq
[(seq ['a'; 'r'; 't'], seq ["tar"]);
(seq ['a'; 'r'; 't'], seq ["rat"]);
(seq ['a'; 'b'; 'r'], seq ["bar"]);
(seq ['b'; 'o'; 'r'], seq ["rob"]);
(seq ['a'; 'r'; 't'], seq ["art"]);
(seq ['b'; 'o'; 'r'], seq ["orb"])]
Why does Seq.groupBy
not, well, group? According to FSI, two equivalent sequences are, in fact, equal:
> let a = seq ['a'; 'r'; 't'];;
> let b = seq ['a'; 'r'; 't'];;
> a = b;;
// val it : bool = true
Why then does Seq.groupBy
not return the following?
seq
[(seq ['a'; 'r'; 't'], seq ["tar"; "rat"; "art"]);
(seq ['a'; 'b'; 'r'], seq ["bar"]);
(seq ['b'; 'o'; 'r'], seq ["rob"; "orb"])]