F # - Why does Seq.map not apply to exceptions?

Provide 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's test it:

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

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

It works as I expected. But if we change the List to Seq in the function, we get a 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 see an exception message in the values ​​object in the debugger, but no exception is thrown ...

Why is that? I need some kind of similar logic in my application and prefer working with sequences.

+4
source share
1 answer

. Seq , Seq.map, , , Seq.map , . , values.

, , , list, , false:

let CollectionHasValidItems keys =
    try
        let values = keys |> Seq.map (fun k -> d.Item k) |> Seq.toList
        true
    with
        | :? System.Collections.Generic.KeyNotFoundException -> false

, List.map Seq.map , , list.

, . , , .

+6

Source: https://habr.com/ru/post/1683519/


All Articles