3

It's odd to me that the following code throws a compile time error. I'm not sure why ContainsKey is returning unit. The documentation says it returns bool.

open System.Collections.Generic    

let mydict = new Dictionary<string,'a>()

if(mydict.ContainsKey "mykey") then
    mydict.["mykey"] = newkey

error FS0001: This expression was expected to have type 'bool' but here has type 'unit'

Am I missing something here?

1
  • 1
    It's not ContainsKey that returns bool. It's the comparison operator = on the next line. Dec 5, 2017 at 16:48

1 Answer 1

6

if is an expression so both branches must have the same type. If the else branch is not specified an empty one of type unit is inserted. This means your then branch must also have type unit. However mydict.["mykey"] = newkey has type bool. If you want to insert a new value for mykey you should use <- instead of =:

if(mydict.ContainsKey "mykey") then
    mydict.["mykey"] <- newkey
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.