Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top