Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concisely creating an IDictionary<_,obj>

Tags:

f#

Is there a shorter way of creating an IDictionary<_,obj>, possibly without boxing every value? This is what I have.

let values =
  [ "a", box 1
    "b", box "foo"
    "c", box true ]
  |> dict

Dictionary<_,obj>.Add can be called without boxing, but I couldn't figure out a way to use it that's shorter than what I have.

I'm hoping for something other than defining a boxing operator.

EDIT

Based on Brian's suggestion, here's one way to do it, but it has its own problems.

let values =
  Seq.zip ["a"; "b"; "c"] ([1; "foo"; true] : obj list) |> dict
like image 888
Daniel Avatar asked Sep 13 '11 20:09

Daniel


2 Answers

Here's a solution, following kvb's suggestion (probably the most concise, and clearest, so far):

let inline (=>) a b = a, box b

let values =
  [ "a" => 1
    "b" => "foo"
    "c" => true ]
  |> dict
like image 91
Daniel Avatar answered Nov 03 '22 16:11

Daniel


Here's the slickest thing I was able to whip up. It has more characters than your boxing version, but possibly feels a little less dirty. Note that the ^ is right-associative (it's the string concat operator inherited from ocaml), which lets it work like ::, and it has stronger precedence than ,, which is why the parenthesis are needed around the tuples.

let inline (^+) (x1:'a,x2:'b) (xl:('a*obj) list) = 
    (x1,box x2)::xl

let values =
  ("a", 1) ^+  ("b", "foo") ^+ ("c", true) ^+ []
  |> dict
like image 3
Stephen Swensen Avatar answered Nov 03 '22 15:11

Stephen Swensen