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.
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;
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With