Mel Padden
Mel Padden

Reputation: 1003

Python-style collections in F#

I'm trying to refactor some python code which I'm using for financial analytics processing into F#, and I'm having difficulty in replicating some of my beloved Python datatypes. For instance in Python I could happily declare a variable like this:

timeSeries = { "20110131":1.5, "20110228":1.5, "20110331":1.5, 
               "20110431":1.5, "20110531":1.5 }

And then throw it around between functions but I don't know the equivalent in F#. I've tried this:

let timeSeries = ( ["20110131":1.5], ["20110228":1.5], ["20110331":1.5], 
                   ["20110431":1.5], ["20110531":1.5] )

But of course it fails... I'm aware that somebody out there is probably spluttering with laughter, but I'm very new to F# and it feels constrictive compared to Python.

I'm familiar with .NET as well, it's just that F# seems to sit somewhere between scripting and "proper" languages like C# and I haven't quite grokked how to use it effectively yet - everything takes ages.

Upvotes: 4

Views: 319

Answers (2)

pad
pad

Reputation: 41290

To be honest, your dictionary declaration in Python doesn't look much different from what you can declare in F#:

let timeSeries = dict [
             "20110131", 1.5; // ',' is tuple delimiter and ';' is list delimiter
             "20110228", 1.5;
             "20110331", 1.5; 
             "20110431", 1.5; 
             "20110531", 1.5; // The last ';' is optional
             ]

Because : is used for type annotation in F#, you couldn't redefine it. But you can create a custom infix operator to make the code more readable and closer to what you usually do in Python:

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

let timeSeries = dict [
         "20110131" => 1.5;
         "20110228" => 1.5;
         "20110331" => 1.5; 
         "20110431" => 1.5; 
         "20110531" => 1.5;
         ]

Upvotes: 9

Daniel
Daniel

Reputation: 47904

You may find this answer helpful. It looks like you want a dictionary. In case you don't already know, F# supports something akin to Python's generator expressions, called sequence expressions [MSDN], which you may also find useful. For example:

let d = dict [ for i in 0 .. 10 -> i, -i ]

Upvotes: 2

Related Questions