tags:

views:

68

answers:

2

Using Seq.cast seems to constantly fail, even for something as simple as the following:

let xor c = Seq.cast c |> Seq.reduce (^^^)
xor [1;3]       // Works, assuming because no cast is necessary
xor ['a';'b']   // Fails
xor [2u]        // Fails

The latter two fail with Specified Cast is not valid. What am I missing?

I'm trying to use Seq.cast to convert a bunch of stuff to uint16, but for some reason it always fails (even if I annotate it with Seq.cast<uint32>). What's up with this?

+5  A: 

I believe this is because Seq.cast will only do type casts, rather that type coercion: you want Seq.map uint32 c |> Seq.reduce (^^^).

The difference between casting and coercing is that while casting changes the static type a value is interpreted as without changing it's dynamic type, (eg: I know this Animal is really a Dog), coercing creates a completely new value ... at least from the language point of view. The split in the CLR seems to be pretty much between value types (coercing) and reference types (casting), which makes it a bit easier to keep straight.

Simon Buchan
Oh I see. Seq.cast is trying to cast the container and not its contents
gradbot
Not quite: while `Seq.cast<uint32> ['a'; 'b']` does cast the `char seq` to a `uint32 seq` (successfully, even), the error happens when the values are enumerated: when the `IEnumerable<uint32>.Current` property is read, it tries and fails to cast the `char` to a `uint32`, when it needs to coerce it, with the `uint32` function.
Simon Buchan
I meant `IEnumerator`, not `IEnumerable` of course. If it's not clear, `Seq` is just an alias for `IEnumerable`.
Simon Buchan
I was afraid of that. I had the `c|> Seq.map uint32 |> Seq.reduce (^^^)` solution, but was wondering why the example failed.Thanks for the response.
MighMoS
+2  A: 

See also

What does this C# code look like in F#? (part one: expressions and statements)

which discusses how casts can mean (at least) 4 different operations in C#, and how each of those different operations maps to specific F# functionality.

Brian
That's a helpful resource, thank you.
MighMoS