structural comparison with List and Array as Sequences

42 views
Skip to first unread message

Robert Kuzelj

unread,
Jun 27, 2016, 8:16:00 AM6/27/16
to F# Discussions
Hi,

can anybody explain what the differences are between an array based sequence and a list based sequence and why the structural comparison works in one but not in the other?

let listCompared = [[1.0; 0.0; 0.0]; [0.0; 1.0; 0.0]] = [[1.0; 0.0; 0.0]; [0.0; 1.0; 0.0]]
let arrayCompared = [|[|1.0; 0.0; 0.0|]; [|0.0; 1.0; 0.0|]|] = [|[|1.0; 0.0; 0.0|]; [|0.0; 1.0; 0.0|]|]

let fromList xs = xs |> List.map List.toSeq |> List.toSeq
let fromArray xs = xs |> Array.map Array.toSeq |> Array.toSeq


let listSeqCompared = (fromList [[1.0; 0.0; 0.0]; [0.0; 1.0; 0.0]]) = (fromList [[1.0; 0.0; 0.0]; [0.0; 1.0; 0.0]])
let arraySeqCompared = (fromArray [|[|1.0; 0.0; 0.0|]; [|0.0; 1.0; 0.0|]|]) = (fromArray [|[|1.0; 0.0; 0.0|]; [|0.0; 1.0; 0.0|]|])
let lazyCompared = seq{yield seq{yield 1.0; yield 0.0; yield 0.0}; yield seq{yield 0.0; yield 1.0; yield 0.0}} = seq{yield seq{yield 1.0; yield 0.0; yield 0.0}; yield seq{yield 0.0; yield 1.0; yield 0.0}}

>>>
val listCompared : bool = true
val arrayCompared : bool = true
val fromList : xs:'a list list -> seq<seq<'a>>
val fromArray : xs:'a [] [] -> seq<seq<'a>>
val listSeqCompared : bool = true
val arraySeqCompared : bool = false
val lazyCompared : bool = false
<<

thx

Robert

Novel Spin

unread,
Jun 28, 2016, 8:51:37 AM6/28/16
to F# Discussions
I did some testing, and it looks like the list gets casted to a seq, while the array is used to create a seq that can't be casted back to an array.  So I'm guessing when you compare two seqs converted from lists, they use the list comparison, but seqs created on their own or converted from arrays use reference comparison.  This is an inconsistency, and I think it should be made consistent.  If you want fromArray to behave like fromList, you can define it like this:
let fromArray (xs : 'a [] []) = xs |> Array.map seq<'a> |> seq<seq<'a>>
Reply all
Reply to author
Forward
0 new messages