Monday, November 8, 2010

Studying F# : Dictionary (a.k.a. Hash or Map)

In F#, there are no types like Dictionary, Hash, Map and so on. We must implement using List, Tuple and dict function.
(This above sentence is incorrect. I correct by thie entry.)

In F#, there are no ways to create Dictionary directly. We must create Dictionary using List, Tuple and dict function.

> let dictionary_1 = dict [ (1, "one"); (2, "two"); (3, "three"); (4, "four") ];;
val dictionary_1 : System.Collections.Generic.IDictionary

> let dictionary_2 = dict [ (1, "one"); (2.0, "two"); (3, "three"); (4, "four")];;
  let dictionary_2 = dict [ (1, "one"); (2.0, "two"); (3, "three"); (4, "four")];;
  ---------------------------------------^^^

stdin(7,40): error FS0001: This expression was expected to have type
    int
but here has type
    float
> let dictionary_3 = dict [ ("one", 1); ("two", 2); ("three", 3.0); ("four", 4)];;
  let dictionary_3 = dict [ ("one", 1); ("two", 2); ("three", 3.0); ("four", 4)];;
  ------------------------------------------------------------^^^

stdin(8,61): error FS0001: This expression was expected to have type
    int
but here has type
    float

Each key and value must be same types.

No comments:

Post a Comment