F # Add value to display result in KeyNotFoundException

type bytesLookup = Map<byte,int list>
type lookupList = bytesLookup list

let maps:bytesLookup = Map.empty

let printArg arg = printfn(Printf.TextWriterFormat<unit>(arg))

let array1 = [|byte(0x02);byte(0xB1);byte(0xA3);byte(0x02);byte(0x18);byte(0x2F)|]

let InitializeNew(maps:bytesLookup,element,index) =
    maps.Add(element,List.empty<int>)(*KeyNotFoundException*)
    maps.[element]

let MapArray (arr:byte[],maps:bytesLookup ) =
   for i in 0..arr.Length do
       match maps.TryFind(arr.[i]) with
        | Some(e) -> i::e
        | None -> InitializeNew(maps,arr.[i],i)

MapArray(array1,maps);

printArg( maps.Count.ToString())

      

An exception

System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. in Microsoft.FSharp.Collections.MapTreeModule.find [TValue, a] (IComparer 2m 1 comparer, TValue k, MapTree

) in Microsoft.FSharp.Collections.FSharpMap 2.get_Item(TKey key) at FSI_0012.MapArray(Byte[] arr, FSharpMap

2) in Script1.fsx: line 16 at. $ FSI_0012.main @ () in Script1.fsx: line 20

In a function, I am trying to initialize a new item on a map with a list of int. I am also trying to insert a new line into the list at the same time.

What am I doing wrong?

+3


source to share


1 answer


F # Map

is an immutable data structure, the method Add

does not change the existing data structure, it returns a new one Map

with the additions you requested.

Note:

let ex1 = 
    let maps = Map.empty<byte, int list>
    maps.Add(1uy, [1]) // compiler warning here!
    maps.[1uy]

      

Two things about this code:



  • It launches System.Collections.Generic.KeyNotFoundException

    on startup

  • This gives the compiler a warning that the string maps.Add...

    must be of a type unit

    , but in fact is of a type Map<byte,int list>

    . Don't ignore the warning!

Now try this:

let ex2 =
    let maps = Map.empty<byte, int list>
    let maps2 = maps.Add(1uy, [1])
    maps2.[1uy]

      

There are no warnings. There are no exceptions. The code works as expected, returning a value [1]

.

+6


source







All Articles