F# - Why Seq.map does not propagate exceptions?

Viewed 316

Imagine the following code:

let d = dict [1, "one"; 2, "two" ]

let CollectionHasValidItems keys =
    try
        let values = keys |> List.map (fun k -> d.Item k)
        true
    with
        | :? KeyNotFoundException -> false

Now let us test it:

let keys1 = [ 1 ; 2 ]
let keys2 = [ 1 ; 2; 3 ]

let result1 = CollectionHasValidItems keys1 // true
let result2 = CollectionHasValidItems keys2 // false

This works as I would expect. But if we change List to Seq in the function, we get different behavior:

let keys1 = seq { 1 .. 2 } 
let keys2 = seq { 1 .. 3 }

let result1 = CollectionHasValidItems keys1 // true
let result2 = CollectionHasValidItems keys2 // true

Here with keys2 I can see the exception message within values object in the debugger but no exception is thrown...

Why is it like this? I need some similar logic in my app and would prefer to work with sequences.

1 Answers
Related