Lecture 14 — Units of measure and type providers
Loading this whole script needs the network. Its packages are downloaded
on first use, the World Bank examples of section 5 ask the World Bank
while the script is being type-checked, and the weather observations of
section 6 are downloaded when the script runs. Without the network the
script does not compile.
Section 1 needs none of that. Its code can be copied into a script of
its own and loaded there.
1 · Units of measure
What is wrong with this?
let speedPlain (distance: float) (time: float) : float = distance / time
let marathonSpeed = speedPlain 7200.0 42195.0
A marathon is 42 195 metres, and it was run in 7200 seconds. The
arguments went in the wrong way round, and the result is not a speed
of anything. The compiler could not tell: both arguments are float.
Measures
A unit of measure is declared as a type with the Measure
attribute. It has no values. It is written in angle brackets after a
number, and it becomes part of the number's type.
[<Measure>] type m // metres
[<Measure>] type s // seconds
[<Measure>] type sqm = m^2 // a derived measure: square metres
let areaOfTriangle (baseLength: float<m>, height: float<m>) : float<sqm> =
baseLength * height / 2.0
let area = areaOfTriangle (2.0<m>, 3.0<m>)
F# Interactive shows the unit in the type:
> areaOfTriangle (2.0<m>, 3.0<m>);;
val it: float<sqm> = 3.0
|
Multiplying two lengths gives m^2, and the result type says sqm.
The compiler has checked that they are the same unit.
Units are multiplied and divided along with the numbers:
let distanceTravelled (speed: float<m/s>) (time: float<s>) : float<m> =
speed * time
let distance = distanceTravelled 10.0<m/s> 60.0<s>
> distanceTravelled 10.0<m/s> 60.0<s>;;
val it: float<m> = 600.0
|
Now the arguments cannot be swapped:
> distanceTravelled 60.0<s> 10.0<m/s>;;
distanceTravelled 60.0<s> 10.0<m/s>;;
------------------^^^^^^^
stdin(23,19): error FS0001: Type mismatch. Expecting a
'float<m/s>'
but given a
'float<s>'
The unit of measure 'm/s' does not match the unit of measure 's'
|
And metres cannot be added to seconds:
> 1.0<m> + 1.0<s>;;
1.0<m> + 1.0<s>;;
---------^^^^^^
stdin(33,10): error FS0001: The unit of measure 's' does not match the unit of measure 'm'
|
Functions that work for any unit
A function can be generic in its unit. Write _ for the unit and let
the compiler work it out:
let sqr (x: float<_>) = x * x
let sumOfSquares x y = sqr x + sqr y
let squares = sumOfSquares 3.0<m> 4.0<m>
> let sqr (x: float<_>) = x * x;;
val sqr: x: float<'u> -> float<'u ^ 2>
> let sumOfSquares x y = sqr x + sqr y;;
val sumOfSquares: x: float<'u> -> y: float<'u> -> float<'u ^ 2>
> sumOfSquares 3.0<m> 4.0<m>;;
val it: float<m ^ 2> = 25.0
|
'u is a unit variable. It is inferred like a type variable: sqr
squares the unit together with the number, and sumOfSquares needs
both arguments in the same unit, because their squares are added.
> sumOfSquares 3.0<m> 4.0<s>;;
sumOfSquares 3.0<m> 4.0<s>;;
--------------------^^^^^^
stdin(31,21): error FS0001: Type mismatch. Expecting a
'float<m>'
but given a
'float<s>'
The unit of measure 'm' does not match the unit of measure 's'
|
Functions of the library are generic in the same way: sqrt 16.0<m^2>
is 4.0<m>, and List.sum [1.5<m>; 2.5<m>] is 4.0<m>.
More units
Any numeric type can carry a unit, and units can have negative powers:
let earthGravity = 9.81f<m/s^2>
[<Measure>] type N // newtons
let atmosphere = 101325.0<N*m^-2>
> let earthGravity = 9.81f<m/s^2>;;
val earthGravity: float32<m/s ^ 2> = 9.81000042f
> let atmosphere = 101325.0<N*m^-2>;;
val atmosphere: float<N/m ^ 2> = 101325.0
|
A derived measure is an abbreviation, not a new unit:
[<Measure>] type a
[<Measure>] type b = a * a
let x = 1<b> / 1<a>
> let x = 1<b> / 1<a>;;
val x: int<b/a> = 1
|
F# Interactive prints b/a. Since b is a * a, that is the unit a,
and x can be used wherever an int<a> is expected.
A range can have units too:
let seconds = [1<s> .. 1<s> .. 5<s>]
> [1<s> .. 1<s> .. 5<s>];;
val it: int<s> list = [1; 2; 3; 4; 5]
|
Units exist only for the compiler
Compare the values the build printed above with the lines of F#
Interactive: the values have no unit. What is the type of 2.0<m>
when the program runs?
let runtimeType = (box 2.0<m>).GetType().Name
A plain Double. Units are checked when the program is compiled and
then erased. They cost nothing at run time, and a running program
cannot ask a number for its unit.
Into and out of units
A number gets a unit by multiplication with a constant that has one.
float takes the unit away:
let width = 2.5 * 1.0<m>
let widthPlain = float width
> let width = 2.5 * 1.0<m>;;
val width: float<m> = 2.5
> float width;;
val it: float = 2.5
|
Converting between units
A conversion is a multiplication by a constant that has a unit of its
own:
[<Measure>] type km
let mPerKm = 1000.0<m/km>
let marathon = 42.195<km>
let marathonMetres = marathon * mPerKm
> marathon * mPerKm;;
val it: float<m> = 42195.0
> marathon * 1000.0;;
val it: float<km> = 42195.0
|
The second line multiplies by a plain 1000.0. The number is right
and the unit is wrong: 42 195 kilometres. With mPerKm the compiler
does the bookkeeping, and the opening example becomes safe:
let speedOf (d: float<m>) (t: float<s>) = d / t
let marathonPace = speedOf (marathon * mPerKm) 7200.0<s>
> speedOf (marathon * mPerKm) 7200.0<s>;;
val it: float<m/s> = 5.860416667
|
2 · Data outside the type system
Inside an F# program everything has a type. Most data does not live
inside the program. It comes from web services as JSON, from files as
CSV, from databases and from workbooks, and none of them know about
F# types. A program has to get the data across that border.
The rest of this script uses packages. F# Interactive downloads them
the first time; later runs use the package cache.
#r "nuget: FSharp.Data, 8.2.0"
#r "nuget: Deedle, 8.1.0"
#r "nuget: XPlot.GoogleCharts, 3.0.1"
#r "nuget: MathNet.Numerics, 5.0.0"
#r "nuget: Newtonsoft.Json, 13.0.4" // newer than the one XPlot asks for
open System
open FSharp.Data
Here is one weather observation as a web service might send it. We
want its temperature. There are three ways to get it.
[<Literal>]
let observationJson = """
{ "station": "Tallinn-Harku",
"time": "2026-06-01T12:00:00Z",
"temperature": 16.7,
"humidity": 55 }
"""
Way 1: look it up by name
Parse the text into a general JSON value and ask for a property by
its name:
let observation = JsonValue.Parse observationJson
let tempByName = observation.GetProperty("temperature").AsFloat ()
The name is a string, and the compiler does not look inside strings.
What happens when it is misspelt?
let misspelt =
try
observation.GetProperty("temprature").AsFloat () |> string
with e -> "failed: " + e.Message
"failed: Didn't find property 'temprature' in {"station":"Tallinn-Harku","time":"2026-06-01T12:00:00Z","temperature":16.7,"humidity":55}"
|
The program compiles and fails when it runs.
Way 2: write the type by hand
Declare a record for the observation and a function that fills it:
type Observation =
{ station: string
time: DateTime
temperature: float
humidity: int }
let toObservation (v: JsonValue) =
{ station = v.GetProperty("station").AsString ()
time = v.GetProperty("time").AsDateTime ()
temperature = v.GetProperty("temperature").AsFloat ()
humidity = v.GetProperty("humidity").AsInteger () }
let byHand = toObservation observation
let tempByHand = byHand.temperature
From here on the compiler helps. A misspelt field is an error before
the program runs:
> byHand.temprature;;
byHand.temprature;;
-------^^^^^^^^^^
stdin(44,8): error FS0039: The type 'Observation' does not define a field, constructor, or member named 'temprature'. Maybe you want one of the following:
temperature
|
But toObservation still has the four names as strings, and we wrote
the record and the conversion ourselves. When the service adds a
field, both have to be edited.
Way 3: a type provider
A type provider makes the type for us, from a sample of the data:
type ObservationJson = JsonProvider<observationJson>
let provided = ObservationJson.GetSample ()
let tempProvided = provided.Temperature
We did not declare Temperature. The provider read the sample,
found a property called temperature and gave the type a property
for it. In an editor, type provided. and look at the completion
list: Station, Time, Temperature and Humidity are there.
A misspelt property is a compile-time error, as with the record:
> provided.Temprature;;
provided.Temprature;;
---------^^^^^^^^^^
stdin(58,10): error FS0039: The type 'Root' does not define a field, constructor, or member named 'Temprature'. Maybe you want one of the following:
Temperature
|
All three ways read the same number:
let sameTemperature =
float tempProvided = tempByName && tempByName = tempByHand
Lookup by name |
none |
fails at run time |
nobody |
Type by hand |
yes |
compile-time error at the use, run-time failure in the conversion |
we do |
Type provider |
yes |
compile-time error |
the provider |
3 · What a type provider is
A type provider is a component that the compiler loads while it is
checking the program. It is given static parameters in angle
brackets, here the sample text, and it answers with types.
> type ObservationJson = JsonProvider<observationJson>;;
type ObservationJson = JsonProvider<...>
|
That is why the parameter has to be known at compile time. The sample
above is a [<Literal>]: a constant the compiler can read. An
ordinary let value would not do.
-
The provider runs at compile time, and in the editor each time
the code is checked. What it needs, it needs then: the sample text
here, a file or a web service for other providers.
-
The data is read at run time, by a library that comes with the
provider.
Provided types are erased
What is provided when the program runs?
let runtimeTypeOfProvided = provided.GetType().FullName
"FSharp.Data.Runtime.BaseTypes.JsonDocument"
|
Not ObservationJson.Root. That type exists for the compiler and the
editor only. In the compiled program it is erased to a general
JSON document of the provider's runtime library, and
provided.Temperature has become a lookup of "temperature" followed
by a conversion to decimal. This is Way 1 again, written by the
provider and checked by the compiler.
Units of measure were erased in the same way: both are compile-time
knowledge that the running program does not carry.
Most providers erase their types. A generative provider adds real
types to the compiled program instead. Providers exist for JSON, XML
and CSV text, for SQL databases, for web services described by WSDL or
OpenAPI, and for single services such as the World Bank (section 5).
4 · Providers on a sample
What the provider infers
The provider infers the types from the sample. Give it a list of two
observations. The second has no humidity, and its temperature is a
whole number:
[<Literal>]
let observationsSample = """
[ { "station": "Tallinn-Harku", "time": "2026-06-01T12:00:00Z",
"temperature": 16.7, "humidity": 55 },
{ "station": "Tallinn-Harku", "time": "2026-06-01T13:00:00Z",
"temperature": 17 } ]
"""
type Observations = JsonProvider<observationsSample>
let humidityOf (o: Observations.Root) = o.Humidity
let temperatureOf (o: Observations.Root) = o.Temperature
> let humidityOf (o: Observations.Root) = o.Humidity;;
val humidityOf: o: JsonProvider<...>.Root -> Option<int>
> let temperatureOf (o: Observations.Root) = o.Temperature;;
val temperatureOf: o: JsonProvider<...>.Root -> decimal
|
-
humidity is missing from one observation, so Humidity is an
option. With the one-observation sample of section 2 it was an int.
-
temperature is 16.7 once and 17 once, so Temperature is a
decimal: the type that holds both.
let humidities =
[ for o in Observations.GetSamples () -> humidityOf o ]
What if every temperature in the sample is a whole number?
type WholeNumbers = JsonProvider<""" { "temperature": 17 } """>
let wholeTemperatureOf (o: WholeNumbers.Root) = o.Temperature
> let wholeTemperatureOf (o: WholeNumbers.Root) = o.Temperature;;
val wholeTemperatureOf: o: JsonProvider<...>.Root -> int
|
An int. The provider knows the sample, not the service.
When the data does not match the sample
The types come from the sample, and the data comes later. Parse an
observation that has no humidity with the type of section 2, whose
sample had one:
let incomplete =
ObservationJson.Parse """ { "station": "Tartu", "temperature": 15.2 } """
let incompleteStation = incomplete.Station
Parsing succeeds, and the properties that are there can be read.
Reading the one that is missing fails:
let missingField =
try
string incomplete.Humidity
with e -> "failed: " + e.Message
"failed: '/humidity' is missing"
|
A temperature with a fraction, read with the type whose sample had
whole numbers only, fails in the same way:
let wrongNumber =
try
let fraction = WholeNumbers.Parse """ { "temperature": 16.7 } """
string fraction.Temperature
with e -> "failed: " + e.Message
"failed: Expecting an Int32 at '/temperature', got 16.7"
|
The compiler checked the program against the sample. It could not
check the data. A good sample shows every shape the data can take:
the missing field, the number with a fraction.
CSV
The CSV provider works in the same way. The sample is a header line
and some rows:
[<Literal>]
let readingsCsv = """Hour,Temperature,Humidity,Height (metre)
12,16.7,55,34
13,17,53,34
14,17.1,,34"""
type Readings = CsvProvider<readingsCsv>
let readings = Readings.GetSample ()
let averageTemperature =
readings.Rows |> Seq.averageBy (fun r -> float r.Temperature)
Each row has a property per column, typed from the values:
> let temperatureAt (r: Readings.Row) = r.Temperature;;
val temperatureAt: r: CsvProvider<...>.Row -> decimal
> let humidityAt (r: Readings.Row) = r.Humidity;;
val humidityAt: r: CsvProvider<...>.Row -> Nullable<int>
> let heightAt (r: Readings.Row) = r.Height;;
val heightAt: r: CsvProvider<...>.Row -> int<UnitSystems.SI.UnitNames.metre>
|
The humidity is empty in one row, so the column is nullable.
Option.ofNullable turns it into an option:
let humidityByHour =
[ for r in readings.Rows -> r.Hour, Option.ofNullable r.Humidity ]
[(12, Some 55); (13, Some 53); (14, None)]
|
The last column is a surprise from section 1. The header says
Height (metre), and the provider gave the column a unit of measure:
the metre of the SI units that come with F#. It is not our m. A
measure is a type, and two types with similar names are two types:
> let ours : int<m> = heightAt (Seq.head readings.Rows);;
let ours : int<m> = heightAt (Seq.head readings.Rows);;
--------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
stdin(61,21): error FS0001: Type mismatch. Expecting a
'int<m>'
but given a
'int<UnitSystems.SI.UnitNames.metre>'
The unit of measure 'm' does not match the unit of measure 'UnitSystems.SI.UnitNames.metre'
|
A program should pick one set of units and use it throughout. This
script uses its own.
5 · The World Bank provider
A provider does not need a sample of text. It can ask a service what
there is. The World Bank publishes thousands of indicators for every
country, and FSharp.Data has a provider for them.
From here on, most examples fetch data. Their code runs when it is
sent to F# Interactive or when the whole script is loaded. The lines
marked > below each block show one run. The numbers will differ
when the World Bank adds a year.
let data = WorldBankData.GetDataContext ()
let capital = data.Countries.Estonia.CapitalCity
> data.Countries.Estonia.CapitalCity;;
val it: string = "Tallinn"
|
Now delete the line and type it again, slowly. After
data.Countries. the editor lists the countries of the world. After
data.Countries.Estonia.Indicators. it lists the indicators. The
provider asked the World Bank for them while the code was being
checked. Nobody wrote these types down.
An indicator is a sequence of years and values:
let estonia = data.Countries.Estonia
let health =
estonia.Indicators.``Current health expenditure (% of GDP)``
let attainmentFemale =
estonia.Indicators.``Educational attainment, at least Bachelor's or equivalent, population 25+, female (%) (cumulative)``
let attainmentMale =
estonia.Indicators.``Educational attainment, at least Bachelor's or equivalent, population 25+, male (%) (cumulative)``
let attainmentTotal =
estonia.Indicators.``Educational attainment, at least Bachelor's or equivalent, population 25+, total (%) (cumulative)``
> health |> Seq.take 3 |> Seq.toList;;
val it: (int * float) list =
[(2000, 5.17029095); (2001, 4.78399181); (2002, 4.70192671)]
> Seq.toList attainmentTotal;;
val it: (int * float) list =
[(2020, 30.84650993); (2021, 31.86923027); (2022, 32.66016806);
(2023, 32.94372764)]
|
The name of an indicator is whatever the World Bank calls it. F#
allows any text as a name between double backticks. The World Bank
has the second indicator for four years only: data from a service has
gaps.
Choosing years
filterYears keeps the points of an indicator from a given year on.
It needs no provider:
let filterYears y (ind: int * float) =
match ind with
| (y', _) when y' >= y -> true
| _ -> false
let fromYear2014 =
[ (2012, 1.5); (2014, 2.5); (2016, 3.5) ] |> List.filter (filterYears 2014)
[(2014, 2.5); (2016, 3.5)]
|
A chart
XPlot draws charts with Google Charts. The options say what the chart
should look like:
open XPlot.GoogleCharts
let chartOptions =
Options (
title = "Proportion of people in tertiary education",
vAxis = Axis (title = "%"),
hAxis = Axis (title = "year"),
seriesType = "line"
)
The chart compares women and men in Estonia and Germany:
let germany = data.Countries.Germany
let attainmentChart =
[ attainmentFemale
attainmentMale
germany.Indicators.``Educational attainment, at least Bachelor's or equivalent, population 25+, female (%) (cumulative)``
germany.Indicators.``Educational attainment, at least Bachelor's or equivalent, population 25+, male (%) (cumulative)`` ]
|> Chart.Combo
|> Chart.WithOptions chartOptions
|> Chart.WithLabels
[ "Female, Estonia"; "Male, Estonia"; "Female, Germany"; "Male, Germany" ]
The chart is a value. Showing it opens a browser window, so that is a
line to send by hand:
> Chart.Show attainmentChart;;
|
The chart has four lines over the years 2014 to 2023. In Estonia a
larger share of women than of men has a degree (39 % against 26 % in
2023). In Germany it is the other way round (27 % against 35 %). The
line for the women of Estonia starts in 2020.
Several countries at once
Each indicator above was fetched when it was first used, one request
after the other. The provider can also give asynchronous indicators:
type WorldBank =
WorldBankDataProvider<"World Development Indicators", Asynchronous=true>
let wb2 = WorldBank.GetDataContext ()
let countries =
[ wb2.Countries.``Arab World``
wb2.Countries.``European Union``
wb2.Countries.Australia
wb2.Countries.``High income`` ]
let populationCountries =
[ wb2.Countries.Estonia
wb2.Countries.Latvia
wb2.Countries.Germany ]
> [ for c in countries -> c.Name ];;
val it: string list =
["Arab World"; "European Union"; "Australia"; "High income"]
|
Regions and income groups are among the countries too.
An indicator of wb2 is an Async. Async.Parallel runs the
requests for all the countries at the same time and gives the results
in the order of the list (Lecture 13):
let attainmentByCountry =
[ for c in populationCountries ->
c.Indicators.``Educational attainment, at least Bachelor's or equivalent, population 25+, total (%) (cumulative)`` ]
|> Async.Parallel
|> Async.RunSynchronously
let attainmentByCountryChart =
attainmentByCountry
|> Chart.Combo
|> Chart.WithOptions chartOptions
|> Chart.WithLegend true
|> Chart.WithLabels [ for c in populationCountries -> c.Name ]
> attainmentByCountry |> Array.map Seq.head;;
val it: (int * float) array =
[|(2020, 30.84650993); (2013, 27.69491005); (2014, 24.18294907)|]
> Chart.Show attainmentByCountryChart;;
|
Three lines: Estonia from 2020, Latvia from 2013, Germany from 2014.
All three rise, to between 30 % and 33 % in 2023.
An asynchronous indicator can be processed inside async { } before
the requests are combined. Here each one is cut down to the years
from 2014:
let attainmentFrom2014 =
[ for c in populationCountries ->
async {
let! ind =
c.Indicators.``Educational attainment, at least Bachelor's or equivalent, population 25+, total (%) (cumulative)``
return Seq.filter (filterYears 2014) ind
} ]
|> Async.Parallel
|> Async.RunSynchronously
let attainmentFrom2014Chart =
attainmentFrom2014
|> Chart.Combo
|> Chart.WithOptions chartOptions
|> Chart.WithLegend true
|> Chart.WithLabels [ for c in populationCountries -> c.Name ]
> attainmentFrom2014 |> Array.map Seq.head;;
val it: (int * float) array =
[|(2020, 30.84650993); (2014, 26.63438034); (2014, 24.18294907)|]
> Chart.Show attainmentFrom2014Chart;;
|
Latvia's line now starts in 2014, like Germany's.
The same for the population, with options of its own:
let chartOptions2 =
Options (
title = "Population",
hAxis = Axis (title = "year"),
seriesType = "line"
)
let populations =
[ for c in populationCountries -> c.Indicators.``Population, total`` ]
|> Async.Parallel
|> Async.RunSynchronously
let populationChart =
populations
|> Chart.Combo
|> Chart.WithOptions chartOptions2
|> Chart.WithLegend true
|> Chart.WithLabels [ for c in populationCountries -> c.Name ]
> populations |> Array.map Seq.length;;
val it: int array = [|66; 66; 66|]
> populations |> Array.map Seq.last;;
val it: (int * float) array =
[|(2025, 1366475.0); (2025, 1847785.0); (2025, 83491249.0)|]
> Chart.Show populationChart;;
|
Sixty-six years for each country. On one chart Germany's 83 million
are a line at the top, and Estonia and Latvia lie on the axis: three
series on one scale are only readable when they are of similar size.
6 · Weather observations from open data
The Estonian Environment Agency publishes the observations of its
weather stations as open data. The
historical data page
of the weather service leads to the service
https://keskkonnaandmed.envir.ee, which answers a request with
JSON. Its table f_kliima_tund has the hourly observations.
There is no provider for this service, and none is needed. Three
rows of its answers, copied on 2 December 2026, are the sample for
the JSON provider:
[<Literal>]
let observationRows = """
[ { "jaam_kood": "AJHARK01", "jaam_nimi": "Tallinn-Harku",
"aasta": 2026, "kuu": 6, "paev": 1, "tund": 0,
"vaartus": 11.80, "element_kood": "TA",
"element_nimi_eng": "Air temperature", "element_yhik_eng": "°C",
"avaandmed_ts": "2026-06-02T02:02:02+00:00" },
{ "jaam_kood": "AJHARK01", "jaam_nimi": "Tallinn-Harku",
"aasta": 2026, "kuu": 6, "paev": 1, "tund": 0,
"vaartus": 80.00, "element_kood": "RH",
"element_nimi_eng": "Relative humidity", "element_yhik_eng": "%",
"avaandmed_ts": "2026-06-02T02:02:02+00:00" },
{ "jaam_kood": "AJHARK01", "jaam_nimi": "Tallinn-Harku",
"aasta": 2026, "kuu": 3, "paev": 12, "tund": 16,
"vaartus": null, "element_kood": "WS10M",
"element_nimi_eng": "Wind speed (10 min avg)", "element_yhik_eng": "m/s",
"avaandmed_ts": "2026-03-13T03:02:04+00:00" } ]
"""
type DataTypesTH = JsonProvider<observationRows>
let row = (DataTypesTH.GetSamples ())[0]
let rowContents =
row.JaamNimi, row.ElementKood, row.Vaartus, row.ElementYhikEng
("Tallinn-Harku", "TA", Some 11.80M, "°C")
|
The names are Estonian, as the service has them: jaam is a station,
aasta, kuu, paev and tund are year, month, day and hour,
vaartus is the value, and element is the quantity that was
measured, with its unit (yhik). The provider made a property of
each: type row. and look.
This table is in long format. A row is not an hour with its
temperature and its humidity. A row is one quantity of one hour: the
first row above is the air temperature at midnight, the second is the
relative humidity at the same time.
A value may be missing
The third row is there for a reason. On 12 March the wind speed was
not recorded at 16:00, and the service sends null for it. Because
the sample has such a row, Vaartus is an option:
> let valueOf (r: DataTypesTH.Root) = r.Vaartus;;
val valueOf: r: JsonProvider<...>.Root -> Option<decimal>
|
When this lecture was prepared, the sample had the first two rows
only. Vaartus was a plain decimal, the script compiled, and
loading the daily values of 2026 stopped with this:
System.Exception: '[187]/vaartus' is missing
|
Row 187 of that answer had no value. The compiler had checked the
program against the sample, and the sample did not show every shape
of the data (section 4).
The time of a row is in four numbers, in UTC:
let toDate (row: DataTypesTH.Root) =
DateTime (row.Aasta, row.Kuu, row.Paev, row.Tund, 0, 0, DateTimeKind.Utc)
let currentDate = toDate row
let currentDateText = currentDate.ToString "yyyy-MM-dd HH:mm"
> currentDate.ToLocalTime().ToString "yyyy-MM-dd HH:mm";;
val it: string = "2026-06-01 03:00"
|
Midnight in UTC is three in the morning in Tallinn in summer.
A month from the service
Nothing was fetched so far: the sample is text in this script. The
data is loaded from an address. This one asks for five quantities of
June 2026 at Tallinn-Harku:
let tallinnHarku =
"https://keskkonnaandmed.envir.ee/f_kliima_tund"
+ "?jaam_kood=eq.AJHARK01&aasta=eq.2026&kuu=eq.6"
+ "&element_kood=in.(TA,TAN1H,TAX1H,RH,WS10M)"
+ "&order=paev,tund"
let month = DataTypesTH.Load tallinnHarku
> month.Length;;
val it: int = 3600
> [ for r in month[0 .. 4] -> r.Tund, r.ElementKood, Option.map float r.Vaartus, r.ElementYhikEng ];;
val it: (int * string * float option * string) list =
[(0, "WS10M", Some 1.8, "m/s"); (0, "TAX1H", Some 11.9, "°C");
(0, "TA", Some 11.8, "°C"); (0, "TAN1H", Some 11.8, "°C");
(0, "RH", Some 80.0, "%")]
|
3600 rows: thirty days of twenty-four hours, with five quantities
each.
The five quantities are the air temperature (TA), its minimum and
maximum over the hour (TAN1H, TAX1H), the relative humidity
(RH) and the wind speed (WS10M).
From rows to hours
To get one value per hour, group the rows by their time (Lecture 12)
and put the quantities of each hour into a map. A row without a value
puts nothing into the map:
let byHour =
month
|> Seq.groupBy toDate
|> Seq.map (fun (date, rows) ->
date,
Map.ofList
[ for r in rows do
for v in Option.toList r.Vaartus -> r.ElementKood, float v ])
|> Seq.toList
> List.length byHour;;
val it: int = 720
> snd (List.head byHour);;
val it: Map<string,float> =
map
[("RH", 80.0); ("TA", 11.8); ("TAN1H", 11.8); ("TAX1H", 11.9);
("WS10M", 1.8)]
|
A quantity that is missing, or that the table does not have at all,
is simply not in the map. So a quantity is looked up with
Map.tryFind, which gives an option:
> Map.tryFind "TA" (snd (List.head byHour));;
val it: float option = Some 11.8
> Map.tryFind "DRQS" (snd (List.head byHour));;
val it: float option = None
|
In June 2026 no hour lacks any of the five. The second lookup asks
for the daily radiation sum, which the hourly table does not have.
The daily table
The same service has a table of daily values, f_kliima_paev. Its
rows have the same properties except the hour, so the same provided
type reads them. This asks for the daily sums of solar radiation
(DRQS) of 2026:
let radiationAddress =
"https://keskkonnaandmed.envir.ee/f_kliima_paev"
+ "?jaam_kood=eq.AJHARK01&aasta=eq.2026"
+ "&element_kood=eq.DRQS&order=kuu,paev"
let radiationRows = DataTypesTH.Load radiationAddress
> radiationRows.Length;;
val it: int = 336
> [ for r in radiationRows[0 .. 2] -> r.Kuu, r.Paev, Option.map float r.Vaartus, r.ElementYhikEng ];;
val it: (int * int * float option * string) list =
[(1, 1, Some 0.96, "MJ/m2"); (1, 2, Some 0.53, "MJ/m2");
(1, 3, Some 0.51, "MJ/m2")]
> [ for r in radiationRows do if r.Vaartus.IsNone then yield r.Kuu, r.Paev ];;
val it: (int * int) list = [(7, 7); (7, 8); (7, 9); (7, 10)]
|
Four days of July have no value. These are the rows that stopped the
first version of this script.
The type fits as long as nobody asks a daily row for its hour:
> toDate radiationRows[0];;
System.Exception: '[0]/tund' is missing
...
Stopped due to error
|
This is section 4 again: the data lacks a property of the sample, and
reading that property fails.
7 · Units on the observations
A unit in the data is text
Every row says what its unit is:
let unitOfRow = row.ElementYhikEng
That is a string. It exists when the program runs, and the compiler
knows nothing about it. A unit of measure is the opposite: the
compiler knows it, and it is gone when the program runs (section 1).
The two meet where the data enters the program. There we attach the
measure, and from there on the compiler checks.
The measures for the observations build on m and s of section 1:
[<Measure>] type ``°C``
[<Measure>] type ``%``
type WD =
{ date: DateTime
hourlyMin: float<``°C``>
hourlyMax: float<``°C``>
hourlyTemp: float<``°C``>
relativeHum: float<``%``>
windSpeed: float<m/s> option }
toEnvData takes an hour, which is a time and a map of quantities,
and makes a record with units. The wind speed is an option, because
it is looked up with Map.tryFind:
let toEnvData (date: DateTime, values: Map<string, float>) =
{ date = date
hourlyMin = values["TAN1H"] * 1.0<``°C``>
hourlyMax = values["TAX1H"] * 1.0<``°C``>
hourlyTemp = values["TA"] * 1.0<``°C``>
relativeHum = values["RH"] * 1.0<``%``>
windSpeed =
Map.tryFind "WS10M" values |> Option.map (fun v -> v * 1.0<m/s>) }
Nothing checks that the row's text said °C where the code
multiplies by one degree Celsius. A careful program compares the text
first and refuses a row whose unit is not the expected one.
A sample to compute on
Twelve hours of the month are written out here, so that the rest of
this section does not depend on the service: the hours 09 to 14 UTC
of 1 and 2 June 2026. The columns are the temperature, its minimum
and maximum, the humidity and the wind speed. One wind speed is left
out on purpose, to have a missing value:
let sampleHour day hour ta tMin tMax rh (wind: float option) =
let values = [ "TA", ta; "TAN1H", tMin; "TAX1H", tMax; "RH", rh ]
let wind = [ for w in Option.toList wind -> "WS10M", w ]
DateTime (2026, 6, day, hour, 0, 0, DateTimeKind.Utc), Map.ofList (values @ wind)
let sampleHours =
[ sampleHour 1 9 15.4 15.1 15.7 61.0 (Some 0.9)
sampleHour 1 10 14.9 14.9 15.5 67.0 (Some 2.3)
sampleHour 1 11 16.1 14.8 16.1 64.0 (Some 0.8)
sampleHour 1 12 16.7 15.7 17.1 55.0 (Some 2.1)
sampleHour 1 13 18.0 16.6 18.3 50.0 (Some 2.1)
sampleHour 1 14 16.5 16.5 18.1 58.0 (Some 1.8)
sampleHour 2 9 18.8 17.7 18.8 54.0 (Some 2.8)
sampleHour 2 10 18.5 18.1 19.4 59.0 (Some 3.2)
sampleHour 2 11 18.5 18.0 19.5 50.0 None
sampleHour 2 12 18.6 18.1 19.5 49.0 (Some 3.0)
sampleHour 2 13 19.6 18.2 19.8 52.0 (Some 2.2)
sampleHour 2 14 18.8 17.7 20.0 59.0 (Some 2.2) ]
let sample = sampleHours |> List.map toEnvData
let warmest = (sample |> List.maxBy (fun o -> o.hourlyTemp)).hourlyTemp
> (sample |> List.maxBy (fun o -> o.hourlyTemp)).hourlyTemp;;
val it: float<°C> = 19.6
|
The mean temperature of each day, by grouping the observations
(Lecture 12):
let dailyMeanTemp =
sample
|> Seq.groupBy (fun o -> o.date.Day)
|> Seq.map (fun (day, os) ->
day, os |> Seq.averageBy (fun o -> o.hourlyTemp))
|> Seq.toList
[(1, 16.26666667); (2, 18.8)]
|
By hand: the six temperatures of 1 June add up to 97.6, and 97.6 / 6
is 16.27. Those of 2 June add up to 112.8, and 112.8 / 6 is 18.8.
The wind speed is an option, so the hours without one are left out
before the mean is taken:
let meanWind =
sample |> List.choose (fun o -> o.windSpeed) |> List.average
> sample |> List.choose (fun o -> o.windSpeed) |> List.average;;
val it: float<m/s> = 2.127272727
|
The whole month
The same function on the hours that came from the service:
let thEnv = byHour |> List.map toEnvData
let tempChart =
thEnv
|> List.map (fun r -> r.date, float r.hourlyTemp)
|> Chart.Line
|> Chart.WithOptions (
Options (title = "Hourly temperature at Tallinn-Harku, June 2026 (°C)"))
> List.length thEnv;;
val it: int = 720
> thEnv |> List.map (fun r -> r.hourlyTemp) |> fun ts -> List.min ts, List.max ts;;
val it: float<°C> * float<°C> = (6.4, 26.1)
> thEnv |> List.averageBy (fun r -> r.hourlyTemp);;
val it: float<°C> = 16.29930556
> Chart.Show tempChart;;
|
The chart has 720 points. The line goes up and down once a day,
between 6.4 °C and 26.1 °C over the month.
Converting radiation
The daily table gives the solar radiation of a day in megajoules per
square metre. Solar panels are counted in kilowatt-hours. How many
megajoules is a kilowatt-hour? The measures can work it out:
[<Measure>] type J // joules
[<Measure>] type W = J/s // a watt is a joule per second
[<Measure>] type kW
[<Measure>] type h // hours
[<Measure>] type MJ
[<Measure>] type kWh = kW h
let wPerKw = 1000.0<W/kW>
let sPerH = 3600.0<s/h>
let jPerMj = 1.0e6<J/MJ>
let mjPerKwh : float<MJ/kWh> = wPerKw * sPerH / jPerMj
The annotation float<MJ/kWh> is a check, not a conversion. The
units of the three constants multiply out to megajoules per
kilowatt-hour, or the line would not compile. Leave one constant out
and see.
The first week of June 2026, as the service gave it:
let sampleRadiation =
[ 14.28; 23.76; 21.21; 24.43; 13.49; 10.36; 26.35 ]
|> List.map (fun v -> v * 1.0<MJ/m^2>)
let toKwh (x: float<MJ/m^2>) : float<kWh/m^2> = x / mjPerKwh
let sampleKwh = sampleRadiation |> List.map toKwh
[3.966666667; 6.6; 5.891666667; 6.786111111; 3.747222222; 2.877777778;
7.319444444]
|
> sampleRadiation |> List.map toKwh;;
val it: float<kWh/m ^ 2> list =
[3.966666667; 6.6; 5.891666667; 6.786111111; 3.747222222; 2.877777778;
7.319444444]
|
By hand: 14.28 / 3.6 is 3.97, and 23.76 / 3.6 is 6.6. The week adds
up to 133.88 megajoules, which is 37.19 kilowatt-hours on each square
metre:
let weekKwh = List.sum sampleKwh
The whole year
The daily rows of 2026 from the service, with dates and units, and
the average daily radiation of each month:
let radiation =
[ for r in radiationRows do
for v in Option.toList r.Vaartus ->
DateTime (r.Aasta, r.Kuu, r.Paev), float v * 1.0<MJ/m^2> ]
|> List.distinct
let monthlyRadiation =
radiation
|> Seq.groupBy (fun (date, _) -> date.Month)
|> Seq.map (fun (month, days) ->
month, days |> Seq.averageBy (fun (_, x) -> toKwh x))
|> Seq.toList
let radiationChartMJ =
radiation
|> List.map (fun (date, x) -> date, float x)
|> Chart.Line
|> Chart.WithOptions (
Options (title = "Daily solar radiation at Tallinn-Harku, 2026 (MJ/m²)"))
let radiationChartKwh =
radiation
|> List.map (fun (date, x) -> date, float (toKwh x))
|> Chart.Line
|> Chart.WithOptions (
Options (title = "Daily solar radiation at Tallinn-Harku, 2026 (kWh/m²)"))
let radiationChartMonthly =
monthlyRadiation
|> List.map (fun (month, x) -> month, float x)
|> Chart.Column
|> Chart.WithOptions (
Options (title = "Average daily solar radiation by month, 2026 (kWh/m²)"))
> List.length radiation;;
val it: int = 330
> monthlyRadiation;;
val it: (int * float<kWh/m ^ 2>) list =
[(1, 0.3808243728); (2, 1.046825397); (3, 2.580913978); (4, 4.212407407);
(5, 5.371594982); (6, 5.515833333); (7, 4.983744856); (8, 4.120250896);
(9, 2.532962963); (10, 1.08046595); (11, 0.3203703704)]
> Chart.Show radiationChartMJ;;
> Chart.Show radiationChartKwh;;
> Chart.Show radiationChartMonthly;;
|
336 rows became 330 days. Four rows had no value, and two days were
in the answer twice, with the same value both times: List.distinct
removes the copies. Data from a service has gaps and repeats, and a
program that reads it has to expect both.
On an average day of June a square metre received 5.5 kilowatt-hours,
and on an average day of November 0.3. The first two charts have the
same shape on different scales. The third has eleven columns, one for
each month so far.
8 · Data frames
Records and lists keep every type and every unit. For exploring data
that is often more than is wanted. A data frame is a table as in
a spreadsheet, or as in pandas for Python. Deedle is a data-frame
library for F#. It has two notions:
-
a series maps keys to values. The key is often a time. A value
may be missing;
-
a frame is a collection of series that share their row keys. A
column is found by its name, and columns may hold values of
different types.
A frame is made from records. Deedle does not know units of measure
and marks a missing number with nan, so the observations get a
plain record first:
open Deedle
type WD2 =
{ date: DateTime
hourlyMin: float
hourlyMax: float
hourlyTemp: float
relativeHum: float
windSpeed: float }
let toEnvData2 (o: WD) : WD2 =
{ date = o.date
hourlyMin = float o.hourlyMin
hourlyMax = float o.hourlyMax
hourlyTemp = float o.hourlyTemp
relativeHum = float o.relativeHum
windSpeed =
match o.windSpeed with
| Some w -> float w
| None -> nan }
Deedle prints numbers in the regional format of the computer. This
helper prints a frame with a decimal point on every computer:
let printFrame (f: Frame<'R, 'C>) =
let saved = Globalization.CultureInfo.CurrentCulture
Globalization.CultureInfo.CurrentCulture <-
Globalization.CultureInfo.InvariantCulture
try f.Print () finally Globalization.CultureInfo.CurrentCulture <- saved
The frame of the twelve sample hours, with the time as the row key:
let dataFrame =
sample
|> List.map toEnvData2
|> Frame.ofRecords
|> Frame.indexRowsDateTime "date"
printFrame dataFrame
hourlyMin hourlyMax hourlyTemp relativeHum windSpeed
2026-06-01 09:00:00 -> 15.1 15.7 15.4 61 0.9
2026-06-01 10:00:00 -> 14.9 15.5 14.9 67 2.3
2026-06-01 11:00:00 -> 14.8 16.1 16.1 64 0.8
2026-06-01 12:00:00 -> 15.7 17.1 16.7 55 2.1
2026-06-01 13:00:00 -> 16.6 18.3 18 50 2.1
2026-06-01 14:00:00 -> 16.5 18.1 16.5 58 1.8
2026-06-02 09:00:00 -> 17.7 18.8 18.8 54 2.8
2026-06-02 10:00:00 -> 18.1 19.4 18.5 59 3.2
2026-06-02 11:00:00 -> 18 19.5 18.5 50 <missing>
2026-06-02 12:00:00 -> 18.1 19.5 18.6 49 3
2026-06-02 13:00:00 -> 18.2 19.8 19.6 52 2.2
2026-06-02 14:00:00 -> 17.7 20 18.8 59 2.2
|
We gave up the units and the record type. We gained columns by name,
missing values and ready-made statistics. A column is a series, and
? gets it by name:
let meanTemp : float = dataFrame?hourlyTemp |> Stats.mean
The name of the column is a string again: dataFrame?hourlyTmp
compiles and fails when it runs. That is the price.
Statistics skip missing values. The mean wind speed is taken over
eleven hours, and it is the number that section 7 computed with
List.choose:
let meanWindOfFrame : float = dataFrame?windSpeed |> Stats.mean
Dropping rows with missing values
RowsDense has the rows in which no value is missing:
let noMissingValues =
dataFrame.RowsDense |> Series.dropMissing |> Frame.ofRows
printFrame noMissingValues
hourlyMin hourlyMax hourlyTemp relativeHum windSpeed
2026-06-01 09:00:00 -> 15.1 15.7 15.4 61 0.9
2026-06-01 10:00:00 -> 14.9 15.5 14.9 67 2.3
2026-06-01 11:00:00 -> 14.8 16.1 16.1 64 0.8
2026-06-01 12:00:00 -> 15.7 17.1 16.7 55 2.1
2026-06-01 13:00:00 -> 16.6 18.3 18 50 2.1
2026-06-01 14:00:00 -> 16.5 18.1 16.5 58 1.8
2026-06-02 09:00:00 -> 17.7 18.8 18.8 54 2.8
2026-06-02 10:00:00 -> 18.1 19.4 18.5 59 3.2
2026-06-02 12:00:00 -> 18.1 19.5 18.6 49 3
2026-06-02 13:00:00 -> 18.2 19.8 19.6 52 2.2
2026-06-02 14:00:00 -> 17.7 20 18.8 59 2.2
|
Eleven rows: the hour without a wind speed is gone.
Grouping
Group the rows by day and take the mean of every column within each
group:
let dailyMeans =
noMissingValues
|> Frame.groupRowsUsing (fun time _ -> time.Day)
|> Frame.getNumericCols
|> Series.mapValues (Stats.levelMean fst)
|> Frame.ofColumns
printFrame dailyMeans
hourlyMin hourlyMax hourlyTemp relativeHum windSpeed
1 -> 15.6 16.8 16.26666666666667 59.166666666666664 1.6666666666666667
2 -> 17.96 19.5 18.86 54.6 2.6799999999999997
|
groupRowsUsing gives every row a second key, the day.
Stats.levelMean fst takes the mean over the rows that agree in the
first key.
By hand: the temperatures of 1 June add up to 97.6, and 97.6 / 6 is
16.27, as in section 7. For 2 June one row was dropped, so five
temperatures are left: 112.8 − 18.5 is 94.3, and 94.3 / 5 is 18.86.
The whole month, and the World Bank again
The same steps on the hours from the service:
let monthFrame =
thEnv
|> List.map toEnvData2
|> Frame.ofRecords
|> Frame.indexRowsDateTime "date"
let dailyMeansOfMonth =
monthFrame
|> Frame.groupRowsUsing (fun time _ -> time.Day)
|> Frame.getNumericCols
|> Series.mapValues (Stats.levelMean fst)
|> Frame.ofColumns
> monthFrame.RowCount;;
val it: int = 720
> dailyMeansOfMonth |> Frame.take 3 |> printFrame;;
hourlyMin hourlyMax hourlyTemp relativeHum windSpeed
1 -> 12.991666666666667 14.041666666666666 13.408333333333333 71.70833333333333 1.6791666666666671
2 -> 13.774999999999999 15.333333333333336 14.55833333333333 70.70833333333333 1.6083333333333336
3 -> 16.816666666666666 18.141666666666666 17.529166666666665 72.20833333333333 1.9500000000000002
|
These are means over all twenty-four hours of a day, so they are
lower than the means of the six midday hours of the sample.
A frame can also be built from series. Each country of the euro area
gives one series, its unemployment rate by year, and frame puts
them side by side as columns. A year that a country lacks is a
missing value:
let euroCountries = data.Regions.``Euro area``
let unemployment =
[ for c in euroCountries.Countries ->
c.Name
=> series c.Indicators.``Unemployment, total (% of total labor force) (modeled ILO estimate)`` ]
|> frame
let recent = unemployment.Rows[2020 ..]
let highestUnemployment =
recent
|> Stats.mean
|> Series.dropMissing
|> Series.sort
|> Series.rev
|> Series.take 5
|> round
> unemployment.RowCount, unemployment.ColumnCount;;
val it: int * int = (35, 21)
> highestUnemployment |> Series.observations |> Seq.toList;;
val it: (string * float) list =
[("Spain", 13.0); ("Greece", 12.0); ("Italy", 8.0); ("Finland", 8.0);
("France", 8.0)]
|
Thirty-five years by twenty-one countries. recent has the rows from
2020 on, Stats.mean of a frame gives the mean of every column, and
the rest sorts the means and keeps the five highest.
A frame of numbers is close to a matrix. Math.NET Numerics has
matrices and vectors:
open MathNet.Numerics.LinearAlgebra
let unemploymentMat =
unemployment
|> Frame.fillMissingWith 0.0
|> Frame.toArray2D
|> Matrix<float>.Build.DenseOfArray
let avgVect =
unemployment
|> Stats.mean
|> Series.fillMissingWith 0.0
|> Series.values
|> Vector<float>.Build.DenseOfEnumerable
let weighted = unemploymentMat * avgVect
> unemploymentMat.RowCount, unemploymentMat.ColumnCount, avgVect.Count;;
val it: int * int * int = (35, 21, 21)
> weighted.Count;;
val it: int = 35
|
The matrix has a row for each year and a column for each country, and
the vector has the mean of each country. Their product has one number
for each year: the sum, over the countries, of that year's rate times
the country's mean. The number means little. The point is that a
frame becomes a matrix in one step, and the dimensions have to agree.
9 · How a provider is written
A type provider is an F# library that the compiler loads. It
implements an interface through which the compiler asks two things:
which types are there, and what code stands for a use of one of their
members. Simplified, in outline:
interface ITypeProvider
GetTypes : unit -> Type[]
GetInvokerExpression : MethodBase * Expr[] -> Expr
Invalidate : event, raised when the types have changed
|
Nobody implements this by hand. The
type provider SDK
has classes for it. A provider of one type with one property looks
like this:
[<TypeProvider>]
type SampleTypeProvider (config: TypeProviderConfig) as this =
inherit TypeProviderForNamespaces (config)
let thisAssembly = Assembly.GetExecutingAssembly ()
// a new type, Samples.GeneratedType
let providedType =
ProvidedTypeDefinition (thisAssembly, "Samples", "GeneratedType", Some typeof<obj>)
do
// a static property Hello that returns a string
ProvidedProperty (
"Hello", typeof<string>, isStatic = true,
getterCode = fun args -> <@@ "Hello, world" @@>)
|> providedType.AddMember
// tell the compiler about the type
this.AddNamespace ("Samples", [ providedType ])
|
This is an outline, not part of the script: a provider is a library
of its own, compiled before the program that uses it. The JSON
provider does the same with more work. It reads the sample, and for
every property it finds it adds a ProvidedProperty.
Code as data
Look at getterCode. The provider does not compute the value of the
property. It hands the compiler the code that will compute it,
between <@@ and @@>. Such a piece of code is a quotation.
A quotation is a value like any other. Its type says what the quoted
code would give:
open FSharp.Quotations
open FSharp.Quotations.Patterns
open FSharp.Quotations.DerivedPatterns
let quoted = <@ 1 + 2 * 3 @>
let quotedText = sprintf "%A" quoted
"Call (None, op_Addition,
[Value (1), Call (None, op_Multiply, [Value (2), Value (3)])])"
|
quoted is an Expr<int>. It is not 7. It is a tree: an addition
whose second argument is a multiplication. A function can take the
tree apart by pattern matching, as with the expression trees of
Lecture 6:
let rec show (e: Expr) =
match e with
| SpecificCall <@ (+) @> (_, _, [ l; r ]) ->
sprintf "(%s + %s)" (show l) (show r)
| SpecificCall <@ (*) @> (_, _, [ l; r ]) ->
sprintf "(%s * %s)" (show l) (show r)
| Value (v, _) -> string v
| _ -> "?"
let rec eval (e: Expr) : int =
match e with
| SpecificCall <@ (+) @> (_, _, [ l; r ]) -> eval l + eval r
| SpecificCall <@ (*) @> (_, _, [ l; r ]) -> eval l * eval r
| Value (v, _) -> unbox v
| _ -> failwith "not an expression of + and *"
let shown = show quoted
let evaluated = eval quoted
The same as the code itself gives:
let direct = 1 + 2 * 3
Code can also be put together. %e splices one quotation into
another:
let twice (e: Expr<int>) = <@ %e + %e @>
let generated = show (twice quoted)
"((1 + (2 * 3)) + (1 + (2 * 3)))"
|
let generatedValue = eval (twice quoted)
twice is a function from code to code. This is code generation in
its smallest form, and it is what a type provider does on a large
scale: from a sample or a service it works out which members there
should be, and for each one it gives the compiler a quotation.
Queries
Quotations are also behind query { }, which is a computation
expression (Lecture 11) with its own operations:
let numbers = [ 3; 8; 1; 12; 7 ]
let large =
query {
for n in numbers do
where (n > 5)
sortBy n
select (n * 10)
}
|> Seq.toList
On a list this does what List.filter, List.sort and List.map
do. The builder of query receives its body as a quotation, though,
and a library can translate that quotation instead of running it. A
database library turns the same lines into SQL and lets the database
do the filtering.
Two providers written at TalTech
10 · Design considerations
What does the provider show? A source can be shown in many ways.
The World Bank provider shows countries first and indicators inside
them. The JSON provider shows properties and nothing else. A good
provider makes the common questions short to write.
A sample or a schema? A sample says what was seen, and a schema
says what can occur. The JSON and CSV providers infer from samples,
and a sample can be incomplete: section 6 needed a row with null
before the type was right. A database or a described web service has
a schema, and a provider that reads it has nothing to guess.
What happens when the source changes? This script shows both
answers.
-
The World Bank provider asks the service while the code is being
checked. If the World Bank renames an indicator, section 5 stops
compiling. The error comes early, which is good. But the script
cannot even be type-checked without the World Bank.
-
The weather type is made from rows in this script. It compiles
whatever the service does. If the service changes a column, the
script fails when it reads the data.
Neither is safe from change. A program that is built on a provider is
built on the provider's source. In 2025 this lecture read the same
observations from a workbook on the weather service's site, with a
provider for workbooks. That workbook is no longer offered there, and
the examples had to be written again for the open-data service.
Caching. A provider that asks a service keeps what it learnt for a
while, so that every check of the code does not ask again. The types
in the editor can therefore be older than the service.
Other tools. The F# data tools go further than this lecture:
there is a provider for R that makes the packages of R callable from
F#, and there are more charting libraries, such as Plotly.NET.
Summary
-
A unit of measure is part of a number's type: the compiler checks
it, and at run time it is gone.
-
A type provider gives types to data that lives outside the
program, while the program is being compiled.
-
A provider infers types from a sample; data that differs from the
sample fails when it is read.
-
Provided types are erased: they exist for the compiler and the
editor, not in the running program.
-
A data frame gives up static types for columns by name, missing
values and aggregates.
Bonus homework, reading and next week
The bonus homework is out this week.
Reading:
The account of type providers in sections 2, 3, 9 and 10 follows
slides by Tomas Petricek.
Next week: functional programming and Lean.
val speedPlain: distance: float -> time: float -> float
val distance: float
Multiple items
val float: value: 'T -> float (requires member op_Explicit)
--------------------
type float = System.Double
--------------------
type float<'Measure> =
float
val time: float
val marathonSpeed: float
Multiple items
type MeasureAttribute =
inherit Attribute
new: unit -> MeasureAttribute
--------------------
new: unit -> MeasureAttribute
type m
type s
type sqm = m ^ 2
val areaOfTriangle: baseLength: float<m> * height: float<m> -> float<sqm>
val baseLength: float<m>
val height: float<m>
val area: float<sqm>
val distanceTravelled: speed: float<m/s> -> time: float<s> -> float<m>
val speed: float<m/s>
val time: float<s>
val distance: float<m>
val sqr: x: float<'u> -> float<'u ^ 2>
val x: float<'u>
val sumOfSquares: x: float<'u> -> y: float<'u> -> float<'u ^ 2>
val y: float<'u>
val squares: float<m ^ 2>
val earthGravity: float32<m/s ^ 2>
type N
val atmosphere: float<N/m ^ 2>
type a
type b = a ^ 2
val x: int<b/a>
val seconds: int<s> list
val runtimeType: string
val box: value: 'T -> objnull
val width: float<m>
val widthPlain: float
type km
val mPerKm: float<m/km>
val marathon: float<km>
val marathonMetres: float<m>
val speedOf: d: float<m> -> t: float<s> -> float<m/s>
val d: float<m>
val t: float<s>
val marathonPace: float<m/s>
namespace System
Multiple items
namespace FSharp
--------------------
namespace Microsoft.FSharp
Multiple items
namespace FSharp.Data
--------------------
namespace Microsoft.FSharp.Data
Multiple items
type LiteralAttribute =
inherit Attribute
new: unit -> LiteralAttribute
--------------------
new: unit -> LiteralAttribute
val observationJson: string = "
{ "station": "Tallinn-Harku",
"time": "2026-06-01T12:00:00Z",
"temperature": 16.7,
"humidity": 55 }
"
val observation: JsonValue
type JsonValue =
| String of string
| Number of decimal
| Float of float
| Record of properties: (string * JsonValue) array
| Array of elements: JsonValue array
| Boolean of bool
| Null
member Request: url: string * ?httpMethod: string * ?headers: (string * string) seq -> HttpResponse
member RequestAsync: url: string * ?httpMethod: string * ?headers: (string * string) seq -> Async<HttpResponse>
member ToString: saveOptions: JsonSaveOptions * ?indentationSpaces: int -> string + 2 overloads
member WriteTo: w: TextWriter * saveOptions: JsonSaveOptions * ?indentationSpaces: int -> unit
static member AsyncLoad: uri: string * ?encoding: Encoding -> Async<JsonValue>
static member Load: stream: Stream -> JsonValue + 2 overloads
static member Parse: text: string -> JsonValue
static member ParseMultiple: text: string -> JsonValue seq
static member TryParse: text: string -> JsonValue option
<summary>
Represents a JSON value. Large numbers that do not fit in the
Decimal type are represented using the Float case, while
smaller numbers are represented as decimals to avoid precision loss.
</summary>
static member JsonValue.Parse: text: string -> JsonValue
val tempByName: float
static member JsonExtensions.GetProperty: x: JsonValue * propertyName: string -> JsonValue
val misspelt: string
Multiple items
val string: value: 'T -> string
--------------------
type string = String
val e: exn
property Exception.Message: string with get
type Observation =
{
station: string
time: DateTime
temperature: float
humidity: int
}
Multiple items
type DateTime =
new: date: DateOnly * time: TimeOnly -> unit + 16 overloads
member Add: value: TimeSpan -> DateTime
member AddDays: value: float -> DateTime
member AddHours: value: float -> DateTime
member AddMicroseconds: value: float -> DateTime
member AddMilliseconds: value: float -> DateTime
member AddMinutes: value: float -> DateTime
member AddMonths: months: int -> DateTime
member AddSeconds: value: float -> DateTime
member AddTicks: value: int64 -> DateTime
...
<summary>Represents an instant in time, typically expressed as a date and time of day.</summary>
--------------------
DateTime ()
(+0 other overloads)
DateTime(ticks: int64) : DateTime
(+0 other overloads)
DateTime(date: DateOnly, time: TimeOnly) : DateTime
(+0 other overloads)
DateTime(ticks: int64, kind: DateTimeKind) : DateTime
(+0 other overloads)
DateTime(date: DateOnly, time: TimeOnly, kind: DateTimeKind) : DateTime
(+0 other overloads)
DateTime(year: int, month: int, day: int) : DateTime
(+0 other overloads)
DateTime(year: int, month: int, day: int, calendar: Globalization.Calendar) : DateTime
(+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int) : DateTime
(+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, kind: DateTimeKind) : DateTime
(+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, calendar: Globalization.Calendar) : DateTime
(+0 other overloads)
Multiple items
val float: value: 'T -> float (requires member op_Explicit)
--------------------
type float = Double
--------------------
type float<'Measure> =
float
Multiple items
val int: value: 'T -> int (requires member op_Explicit)
--------------------
type int = int32
--------------------
type int<'Measure> =
int
val toObservation: v: JsonValue -> Observation
val v: JsonValue
val byHand: Observation
val tempByHand: float
Observation.temperature: float
type ObservationJson = JsonProvider<...>
type JsonProvider
<summary>Typed representation of a JSON document.</summary>
<param name='Sample'>Location of a JSON sample file or a string containing a sample JSON document.</param>
<param name='SampleIsList'>If true, sample should be a list of individual samples for the inference.</param>
<param name='RootName'>The name to be used to the root type. Defaults to `Root`.</param>
<param name='Culture'>The culture used for parsing numbers and dates. Defaults to the invariant culture.</param>
<param name='Encoding'>The encoding used to read the sample. You can specify either the character set name or the codepage number. Defaults to UTF8 for files, and to ISO-8859-1 the for HTTP requests, unless `charset` is specified in the `Content-Type` response header.</param>
<param name='ResolutionFolder'>A directory that is used when resolving relative file references (at design time and in hosted execution).</param>
<param name='EmbeddedResource'>When specified, the type provider first attempts to load the sample from the specified resource
(e.g. 'MyCompany.MyAssembly, resource_name.json'). This is useful when exposing types generated by the type provider.</param>
<param name='InferTypesFromValues'>
This parameter is deprecated. Please use InferenceMode instead.
If true, turns on additional type inference from values.
(e.g. type inference infers string values such as "123" as ints and values constrained to 0 and 1 as booleans.)</param>
<param name='PreferDictionaries'>If true, json records are interpreted as dictionaries when the names of all the fields are inferred (by type inference rules) into the same non-string primitive type.</param>
<param name='InferenceMode'>Possible values:
| NoInference -> Inference is disabled. All values are inferred as the most basic type permitted for the value (i.e. string or number or bool).
| ValuesOnly -> Types of values are inferred from the Sample. Inline schema support is disabled. This is the default.
| ValuesAndInlineSchemasHints -> Types of values are inferred from both values and inline schemas. Inline schemas are special string values that can define a type and/or unit of measure. Supported syntax: typeof<type> or typeof{type} or typeof<type<measure>> or typeof{type{measure}}. Valid measures are the default SI units, and valid types are <c>int</c>, <c>int64</c>, <c>bool</c>, <c>float</c>, <c>decimal</c>, <c>date</c>, <c>datetimeoffset</c>, <c>timespan</c>, <c>guid</c> and <c>string</c>.
| ValuesAndInlineSchemasOverrides -> Same as ValuesAndInlineSchemasHints, but value inferred types are ignored when an inline schema is present.
</param>
<param name='Schema'>Location of a JSON Schema file or a string containing a JSON Schema document. When specified, Sample and SampleIsList must not be used.</param>
<param name='PreferDateOnly'>When true on .NET 6+, date-only strings (e.g. "2023-01-15") are inferred as DateOnly and time-only strings as TimeOnly. Defaults to false for backward compatibility.</param>
<param name='UseOriginalNames'>When true, JSON property names are used as-is for generated property names instead of being normalized to PascalCase. Defaults to false.</param>
<param name='OmitNullFields'>When true, optional fields with value None are omitted from the generated JSON rather than serialized as null. Defaults to false.</param>
<param name='PreferOptionals'>When set to true (default), inference will use the option type for missing or null values. When false, inference will prefer to use empty string or double.NaN for missing values where possible, matching the default CsvProvider behavior.</param>
<param name='PreferDateTimeOffset'>When true, date-time strings without an explicit timezone offset are inferred as DateTimeOffset (using the local offset) instead of DateTime. Defaults to false.</param>
<param name='ExceptionIfMissing'>When true, accessing a non-optional field that is missing in the JSON data raises an exception instead of returning a default value (empty string for string, NaN for float). Defaults to false for backward compatibility.</param>
val provided: JsonProvider<...>.Root
JsonProvider<...>.GetSample() : JsonProvider<...>.Root
val tempProvided: decimal
property JsonProvider<...>.Root.Temperature: decimal with get
val sameTemperature: bool
val runtimeTypeOfProvided: string
val observationsSample: string = "
[ { "station": "Tallinn-Harku", "time": "2026-06-01T12:00:00Z",
"temperature": 16.7, "humidity": 55 },
{ "station": "Tallinn-Harku", "time": "2026-06-01T13:00:00Z",
"temperature": 17 } ]
"
type Observations = JsonProvider<...>
val humidityOf: o: JsonProvider<...>.Root -> Option<int>
val o: JsonProvider<...>.Root
type Root =
inherit IJsonDocument
new: station: string * time: DateTimeOffset * temperature: decimal * humidity: Option<int> -> Root + 1 overload
member WithHumidity: humidity: Option<int> -> Root
member WithStation: station: string -> Root
member WithTemperature: temperature: decimal -> Root
member WithTime: time: DateTimeOffset -> Root
member Humidity: Option<int>
member Station: string
member Temperature: decimal
member Time: DateTimeOffset
property JsonProvider<...>.Root.Humidity: Option<int> with get
val temperatureOf: o: JsonProvider<...>.Root -> decimal
val humidities: Option<int> list
JsonProvider<...>.GetSamples() : JsonProvider<...>.Root array
type WholeNumbers = JsonProvider<...>
val wholeTemperatureOf: o: JsonProvider<...>.Root -> int
type Root =
inherit IJsonDocument
new: temperature: int -> Root + 1 overload
member WithTemperature: temperature: int -> Root
member Temperature: int
property JsonProvider<...>.Root.Temperature: int with get
val incomplete: JsonProvider<...>.Root
JsonProvider<...>.Parse(text: string) : JsonProvider<...>.Root
Parses the specified JSON string
val incompleteStation: string
property JsonProvider<...>.Root.Station: string with get
val missingField: string
property JsonProvider<...>.Root.Humidity: int with get
val wrongNumber: string
val fraction: JsonProvider<...>.Root
val readingsCsv: string = "Hour,Temperature,Humidity,Height (metre)
12,16.7,55,34
13,17,53,34
14,17.1,,34"
type Readings = CsvProvider<...>
type CsvProvider
<summary>Typed representation of a CSV file.</summary>
<param name='Sample'>Location of a CSV sample file or a string containing a sample CSV document.</param>
<param name='Separators'>Column delimiter(s). Defaults to <c>,</c>.</param>
<param name='InferRows'>Number of rows to use for inference. Defaults to <c>1000</c>. If this is zero, all rows are used.</param>
<param name='Schema'>Optional column types, in a comma separated list. Valid types are <c>int</c>, <c>int64</c>, <c>bool</c>, <c>float</c>, <c>decimal</c>, <c>date</c>, <c>datetimeoffset</c>, <c>timespan</c>, <c>guid</c>, <c>string</c>, <c>int?</c>, <c>int64?</c>, <c>bool?</c>, <c>float?</c>, <c>decimal?</c>, <c>date?</c>, <c>datetimeoffset?</c>, <c>timespan?</c>, <c>guid?</c>, <c>int option</c>, <c>int64 option</c>, <c>bool option</c>, <c>float option</c>, <c>decimal option</c>, <c>date option</c>, <c>datetimeoffset option</c>, <c>timespan option</c>, <c>guid option</c> and <c>string option</c>.
You can also specify a unit and the name of the column like this: <c>Name (type<unit>)</c>, or you can override only the name. If you don't want to specify all the columns, you can reference the columns by name like this: <c>ColumnName=type</c>.</param>
<param name='HasHeaders'>Whether the sample contains the names of the columns as its first line.</param>
<param name='IgnoreErrors'>Whether to ignore rows that have the wrong number of columns or which can't be parsed using the inferred or specified schema. Otherwise an exception is thrown when these rows are encountered.</param>
<param name='SkipRows'>Skips the first n rows of the CSV file.</param>
<param name='AssumeMissingValues'>When set to true, the type provider will assume all columns can have missing values, even if in the provided sample all values are present. Defaults to false.</param>
<param name='PreferOptionals'>When set to true, inference will prefer to use the option type instead of nullable types, <c>double.NaN</c> or <c>""</c> for missing values. Defaults to false.</param>
<param name='Quote'>The quotation mark (for surrounding values containing the delimiter). Defaults to <c>"</c>.</param>
<param name='MissingValues'>The set of strings recognized as missing values specified as a comma-separated string (e.g., "NA,N/A"). Defaults to <c>NaN,NA,N/A,#N/A,:,-,TBA,TBD</c>.</param>
<param name='CacheRows'>Whether the rows should be caches so they can be iterated multiple times. Defaults to true. Disable for large datasets.</param>
<param name='Culture'>The culture used for parsing numbers and dates. Defaults to the invariant culture.</param>
<param name='Encoding'>The encoding used to read the sample. You can specify either the character set name or the codepage number. Defaults to UTF8 for files, and to ISO-8859-1 the for HTTP requests, unless <c>charset</c> is specified in the <c>Content-Type</c> response header.</param>
<param name='ResolutionFolder'>A directory that is used when resolving relative file references (at design time and in hosted execution).</param>
<param name='EmbeddedResource'>When specified, the type provider first attempts to load the sample from the specified resource
(e.g. 'MyCompany.MyAssembly, resource_name.csv'). This is useful when exposing types generated by the type provider.</param>
<param name='PreferDateOnly'>When true on .NET 6+, date-only strings are inferred as DateOnly and time-only strings as TimeOnly. Defaults to false for backward compatibility.</param>
<param name='StrictBooleans'>When true, only <c>true</c> and <c>false</c> (case-insensitive) are inferred as boolean. Values such as <c>0</c>, <c>1</c>, <c>yes</c>, and <c>no</c> are treated as integers or strings respectively. Defaults to false.</param>
<param name='UseOriginalNames'>When true, CSV column header names are used as-is for generated property names instead of being normalized (e.g. capitalizing the first letter). Defaults to false.</param>
<param name='PreferDateTimeOffset'>When true, date-time strings without an explicit timezone offset are inferred as DateTimeOffset (using the local offset) instead of DateTime. Defaults to false.</param>
val readings: CsvProvider<...>
CsvProvider<...>.GetSample() : CsvProvider<...>
val averageTemperature: float
property Runtime.CsvFile.Rows: CsvProvider<...>.Row seq with get
<summary>
The rows with data
</summary>
module Seq
from Microsoft.FSharp.Collections
val averageBy: projection: ('T -> 'U) -> source: 'T seq -> 'U (requires member (+) and member DivideByInt and member Zero)
val r: CsvProvider<...>.Row
property CsvProvider<...>.Row.Temperature: decimal with get
val humidityByHour: (int * int option) list
property CsvProvider<...>.Row.Hour: int with get
module Option
from Microsoft.FSharp.Core
val ofNullable: value: Nullable<'T> -> 'T option (requires default constructor and value type and 'T :> ValueType)
property CsvProvider<...>.Row.Humidity: Nullable<int> with get
val data: WorldBankData.ServiceTypes.WorldBankDataService
type WorldBankData =
static member GetDataContext: unit -> WorldBankDataService
nested type ServiceTypes
WorldBankData.GetDataContext() : WorldBankData.ServiceTypes.WorldBankDataService
val capital: string
property WorldBankData.ServiceTypes.WorldBankDataService.Countries: WorldBankData.ServiceTypes.Countries with get
property WorldBankData.ServiceTypes.Countries.Estonia: WorldBankData.ServiceTypes.Country with get
The data for country 'Estonia'
property Runtime.WorldBank.Country.CapitalCity: string with get
<summary>
Get the capital city of the country
</summary>
val estonia: WorldBankData.ServiceTypes.Country
val health: Runtime.WorldBank.Indicator
property WorldBankData.ServiceTypes.Country.Indicators: WorldBankData.ServiceTypes.Indicators with get
<summary>The indicators for the country</summary>
val attainmentFemale: Runtime.WorldBank.Indicator
val attainmentMale: Runtime.WorldBank.Indicator
val attainmentTotal: Runtime.WorldBank.Indicator
val filterYears: y: int -> int * float -> bool
val y: int
val ind: int * float
val y': int
val fromYear2014: (int * float) list
Multiple items
module List
from Microsoft.FSharp.Collections
--------------------
type List<'T> =
| op_Nil
| op_ColonColon of Head: 'T * Tail: 'T list
interface IReadOnlyList<'T>
interface IReadOnlyCollection<'T>
interface IEnumerable
interface IEnumerable<'T>
member GetReverseIndex: rank: int * offset: int -> int
member GetSlice: startIndex: int option * endIndex: int option -> 'T list
static member Cons: head: 'T * tail: 'T list -> 'T list
member Head: 'T
member IsEmpty: bool
member Item: index: int -> 'T with get
...
val filter: predicate: ('T -> bool) -> list: 'T list -> 'T list
namespace XPlot
namespace XPlot.GoogleCharts
val chartOptions: Options
Multiple items
type Options =
new: unit -> Options
member ShouldSerializeaggregationTarget: unit -> bool
member ShouldSerializeallValuesSuffix: unit -> bool
member ShouldSerializeallowHtml: unit -> bool
member ShouldSerializealternatingRowStyle: unit -> bool
member ShouldSerializeanimation: unit -> bool
member ShouldSerializeannotations: unit -> bool
member ShouldSerializeannotationsWidth: unit -> bool
member ShouldSerializeareaOpacity: unit -> bool
member ShouldSerializeavoidOverlappingGridLines: unit -> bool
...
--------------------
new: unit -> Options
Multiple items
type Axis =
new: unit -> Axis
member ShouldSerializeallowContainerBoundaryTextCufoff: unit -> bool
member ShouldSerializebaseline: unit -> bool
member ShouldSerializebaselineColor: unit -> bool
member ShouldSerializedirection: unit -> bool
member ShouldSerializeformat: unit -> bool
member ShouldSerializegridlines: unit -> bool
member ShouldSerializelogScale: unit -> bool
member ShouldSerializemaxAlternation: unit -> bool
member ShouldSerializemaxTextLines: unit -> bool
...
--------------------
new: unit -> Axis
val germany: WorldBankData.ServiceTypes.Country
property WorldBankData.ServiceTypes.Countries.Germany: WorldBankData.ServiceTypes.Country with get
The data for country 'Germany'
val attainmentChart: GoogleChart
type Chart =
static member Annotation: data: (DateTime * #value * string * string) seq * ?Labels: string seq * ?Options: Options -> GoogleChart + 1 overload
static member Area: data: #value seq * ?Labels: string seq * ?Options: Options -> GoogleChart + 2 overloads
static member Bar: data: #value seq * ?Labels: string seq * ?Options: Options -> GoogleChart + 2 overloads
static member Bubble: data: (string * #value * #value) seq * ?Labels: string seq * ?Options: Options -> GoogleChart + 2 overloads
static member Calendar: data: (DateTime * #value) seq * ?Labels: string seq * ?Options: Options -> GoogleChart
static member Candlestick: data: (#key * #value * #value * #value * #value) seq * ?Labels: string seq * ?Options: Options -> GoogleChart + 1 overload
static member Column: data: #value seq * ?Labels: string seq * ?Options: Options -> GoogleChart + 2 overloads
static member Combo: data: #seq<'K * 'V> seq * ?Labels: string seq * ?Options: Options -> GoogleChart (requires 'K :> key and 'V :> value)
static member Gauge: data: (string * #value) seq * ?Labels: string seq * ?Options: Options -> GoogleChart
static member Geo: data: (string * #value) seq * ?Labels: string seq * ?Options: Options -> GoogleChart + 4 overloads
...
static member Chart.Combo: data: #seq<'K * 'V> seq * ?Labels: string seq * ?Options: Options -> GoogleChart (requires 'K :> key and 'V :> value)
static member Chart.WithOptions: options: Options -> chart: GoogleChart -> GoogleChart
static member Chart.WithLabels: labels: string seq -> chart: GoogleChart -> GoogleChart
type WorldBank = WorldBankDataProvider<...>
type WorldBankDataProvider
<summary>Typed representation of WorldBank data with additional configuration parameters. See https://www.worldbank.org for terms and conditions.</summary>
<param name='Sources'>The World Bank data sources to include, separated by semicolons. Defaults to <c>World Development Indicators;Global Financial Development</c>.
If an empty string is specified, includes all data sources.</param>
<param name='Asynchronous'>Generate asynchronous calls. Defaults to false.</param>
val wb2: WorldBankDataProvider<...>.ServiceTypes.WorldBankDataService
WorldBankDataProvider<...>.GetDataContext() : WorldBankDataProvider<...>.ServiceTypes.WorldBankDataService
val countries: WorldBankDataProvider<...>.ServiceTypes.Country list
property WorldBankDataProvider<...>.ServiceTypes.WorldBankDataService.Countries: WorldBankDataProvider<...>.ServiceTypes.Countries with get
property WorldBankDataProvider<...>.ServiceTypes.Countries.Australia: WorldBankDataProvider<...>.ServiceTypes.Country with get
The data for country 'Australia'
val populationCountries: WorldBankDataProvider<...>.ServiceTypes.Country list
property WorldBankDataProvider<...>.ServiceTypes.Countries.Estonia: WorldBankDataProvider<...>.ServiceTypes.Country with get
The data for country 'Estonia'
property WorldBankDataProvider<...>.ServiceTypes.Countries.Latvia: WorldBankDataProvider<...>.ServiceTypes.Country with get
The data for country 'Latvia'
property WorldBankDataProvider<...>.ServiceTypes.Countries.Germany: WorldBankDataProvider<...>.ServiceTypes.Country with get
The data for country 'Germany'
val attainmentByCountry: Runtime.WorldBank.Indicator array
val c: WorldBankDataProvider<...>.ServiceTypes.Country
property WorldBankDataProvider<...>.ServiceTypes.Country.Indicators: WorldBankDataProvider<...>.ServiceTypes.Indicators with get
<summary>The indicators for the country</summary>
Multiple items
type Async =
static member AsBeginEnd: computation: ('Arg -> Async<'T>) -> ('Arg * AsyncCallback * objnull -> IAsyncResult) * (IAsyncResult -> 'T) * (IAsyncResult -> unit)
static member AwaitEvent: event: IEvent<'Del,'T> * ?cancelAction: (unit -> unit) -> Async<'T> (requires delegate and 'Del :> Delegate and 'Del: not null)
static member AwaitIAsyncResult: iar: IAsyncResult * ?millisecondsTimeout: int -> Async<bool>
static member AwaitTask: task: Task<'T> -> Async<'T> + 1 overload
static member AwaitWaitHandle: waitHandle: WaitHandle * ?millisecondsTimeout: int -> Async<bool>
static member CancelDefaultToken: unit -> unit
static member Catch: computation: Async<'T> -> Async<Choice<'T,exn>>
static member Choice: computations: Async<'T option> seq -> Async<'T option>
static member FromBeginEnd: beginAction: (AsyncCallback * objnull -> IAsyncResult) * endAction: (IAsyncResult -> 'T) * ?cancelAction: (unit -> unit) -> Async<'T> + 3 overloads
static member FromContinuations: callback: (('T -> unit) * (exn -> unit) * (OperationCanceledException -> unit) -> unit) -> Async<'T>
...
--------------------
type Async<'T>
static member Async.Parallel: computations: Async<'T> seq -> Async<'T array>
static member Async.Parallel: computations: Async<'T> seq * ?maxDegreeOfParallelism: int -> Async<'T array>
static member Async.RunSynchronously: computation: Async<'T> * ?timeout: int * ?cancellationToken: Threading.CancellationToken -> 'T
val attainmentByCountryChart: GoogleChart
static member Chart.WithLegend: enabled: bool -> chart: GoogleChart -> GoogleChart
property Runtime.WorldBank.Country.Name: string with get
<summary>
Get the name of the country
</summary>
val attainmentFrom2014: (int * float) seq array
val async: AsyncBuilder
val ind: Runtime.WorldBank.Indicator
val filter: predicate: ('T -> bool) -> source: 'T seq -> 'T seq
val attainmentFrom2014Chart: GoogleChart
val chartOptions2: Options
val populations: Runtime.WorldBank.Indicator array
val populationChart: GoogleChart
val observationRows: string = "
[ { "jaam_kood": "AJHARK01", "jaam_nimi": "Tallinn-Harku",
"aasta": 2026, "kuu": 6, "paev": 1, "tund": 0,
"vaartus": 11.80, "element_kood": "TA",
"element_nimi_eng": "Air temperature", "element_yhik_eng": "°C",
"avaandmed_ts": "2026-06-02T02:02:02+00:00" },
{ "jaam_kood": "AJHARK01", "jaam_nimi": "Tallinn-Harku",
"aasta": 2026, "kuu": 6, "paev": 1, "tund": 0,
"vaartus": 80.00, "element_kood": "RH",
"element_nimi_eng": "Relative humidity", "element_yhik_eng": "%",
"avaandmed_ts": "2026-06-02T02:02:02+00:00" },
{ "jaam_kood": "AJHARK01", "jaam_nimi": "Tallinn-Harku",
"aasta": 2026, "kuu": 3, "paev": 12, "tund": 16,
"vaartus": null, "element_kood": "WS10M",
"element_nimi_eng": "Wind speed (10 min avg)", "element_yhik_eng": "m/s",
"avaandmed_ts": "2026-03-13T03:02:04+00:00" } ]
"
type DataTypesTH = JsonProvider<...>
val row: JsonProvider<...>.Root
val rowContents: string * string * Option<decimal> * string
property JsonProvider<...>.Root.JaamNimi: string with get
property JsonProvider<...>.Root.ElementKood: string with get
property JsonProvider<...>.Root.Vaartus: Option<decimal> with get
property JsonProvider<...>.Root.ElementYhikEng: string with get
val toDate: row: JsonProvider<...>.Root -> DateTime
type Root =
inherit IJsonDocument
new: jaamKood: string * jaamNimi: string * aasta: int * kuu: int * paev: int * tund: int * vaartus: Option<decimal> * elementKood: string * elementNimiEng: string * elementYhikEng: string * avaandmedTs: DateTimeOffset -> Root + 1 overload
member WithAasta: aasta: int -> Root
member WithAvaandmedTs: avaandmedTs: DateTimeOffset -> Root
member WithElementKood: elementKood: string -> Root
member WithElementNimiEng: elementNimiEng: string -> Root
member WithElementYhikEng: elementYhikEng: string -> Root
member WithJaamKood: jaamKood: string -> Root
member WithJaamNimi: jaamNimi: string -> Root
member WithKuu: kuu: int -> Root
...
property JsonProvider<...>.Root.Aasta: int with get
property JsonProvider<...>.Root.Kuu: int with get
property JsonProvider<...>.Root.Paev: int with get
property JsonProvider<...>.Root.Tund: int with get
type DateTimeKind =
| Unspecified = 0
| Utc = 1
| Local = 2
<summary>Specifies whether a <see cref="T:System.DateTime" /> object represents a local time, a Coordinated Universal Time (UTC), or is not specified as either local time or UTC.</summary>
field DateTimeKind.Utc: DateTimeKind = 1
val currentDate: DateTime
val currentDateText: string
DateTime.ToString() : string
DateTime.ToString( format: string) : string
DateTime.ToString(provider: IFormatProvider) : string
DateTime.ToString( format: string, provider: IFormatProvider) : string
val tallinnHarku: string
val month: JsonProvider<...>.Root array
JsonProvider<...>.Load(value: JsonValue) : JsonProvider<...>.Root array
Loads JSON from the specified value
JsonProvider<...>.Load(uri: string) : JsonProvider<...>.Root array
Loads JSON from the specified uri
JsonProvider<...>.Load(reader: IO.TextReader) : JsonProvider<...>.Root array
Loads JSON from the specified reader
JsonProvider<...>.Load(stream: IO.Stream) : JsonProvider<...>.Root array
Loads JSON from the specified stream
val byHour: (DateTime * Map<string,float>) list
val groupBy: projection: ('T -> 'Key) -> source: 'T seq -> ('Key * 'T seq) seq (requires equality)
val map: mapping: ('T -> 'U) -> source: 'T seq -> 'U seq
val date: DateTime
val rows: JsonProvider<...>.Root seq
Multiple items
union case ChartGallery.Map: ChartGallery
--------------------
module Map
from Microsoft.FSharp.Collections
--------------------
type Map<'Key,'Value (requires comparison)> =
interface IReadOnlyDictionary<'Key,'Value>
interface IReadOnlyCollection<KeyValuePair<'Key,'Value>>
interface IEnumerable
interface IStructuralEquatable
interface IComparable
interface IEnumerable<KeyValuePair<'Key,'Value>>
interface ICollection<KeyValuePair<'Key,'Value>>
interface IDictionary<'Key,'Value>
new: elements: ('Key * 'Value) seq -> Map<'Key,'Value>
member Add: key: 'Key * value: 'Value -> Map<'Key,'Value>
...
--------------------
new: elements: ('Key * 'Value) seq -> Map<'Key,'Value>
val ofList: elements: ('Key * 'T) list -> Map<'Key,'T> (requires comparison)
val r: JsonProvider<...>.Root
val v: decimal
val toList: option: 'T option -> 'T list
val toList: source: 'T seq -> 'T list
val radiationAddress: string
val radiationRows: JsonProvider<...>.Root array
val unitOfRow: string
type WD =
{
date: DateTime
hourlyMin: float<°C>
hourlyMax: float<°C>
hourlyTemp: float<°C>
relativeHum: float<%>
windSpeed: float<m/s> option
}
type 'T option = Option<'T>
val toEnvData: date: DateTime * values: Map<string,float> -> WD
val values: Map<string,float>
val tryFind: key: 'Key -> table: Map<'Key,'T> -> 'T option (requires comparison)
val map: mapping: ('T -> 'U) -> option: 'T option -> 'U option
val v: float
val sampleHour: day: int -> hour: int -> ta: float -> tMin: float -> tMax: float -> rh: float -> wind: float option -> DateTime * Map<string,float>
val day: int
val hour: int
val ta: float
val tMin: float
val tMax: float
val rh: float
val wind: float option
val values: (string * float) list
val wind: (string * float) list
val w: float
val sampleHours: (DateTime * Map<string,float>) list
union case Option.Some: Value: 'T -> Option<'T>
union case Option.None: Option<'T>
val sample: WD list
val map: mapping: ('T -> 'U) -> list: 'T list -> 'U list
val warmest: float<°C>
val maxBy: projection: ('T -> 'U) -> list: 'T list -> 'T (requires comparison)
val o: WD
WD.hourlyTemp: float<°C>
val dailyMeanTemp: (int * float<°C>) list
WD.date: DateTime
property DateTime.Day: int with get
<summary>Gets the day of the month represented by this instance.</summary>
<returns>The day component, expressed as a value between 1 and 31.</returns>
val os: WD seq
val meanWind: float<m/s>
val choose: chooser: ('T -> 'U option) -> list: 'T list -> 'U list
WD.windSpeed: float<m/s> option
val average: list: 'T list -> 'T (requires member (+) and member DivideByInt and member Zero)
val thEnv: WD list
val tempChart: GoogleChart
val r: WD
static member Chart.Line: data: #seq<'K * 'V> seq * ?Labels: string seq * ?Options: Options -> GoogleChart (requires 'K :> key and 'V :> value)
static member Chart.Line: data: (#key * #value) seq * ?Labels: string seq * ?Options: Options -> GoogleChart
static member Chart.Line: data: #value seq * ?Labels: string seq * ?Options: Options -> GoogleChart
type J
type W = J/s
type kW
type h
type MJ
type kWh = h kW
val wPerKw: float<W/kW>
val sPerH: float<s/h>
val jPerMj: float<J/MJ>
val mjPerKwh: float<MJ/kWh>
val sampleRadiation: float<MJ/m ^ 2> list
val toKwh: x: float<MJ/m ^ 2> -> float<kWh/m ^ 2>
val x: float<MJ/m ^ 2>
val sampleKwh: float<kWh/m ^ 2> list
val weekKwh: float<kWh/m ^ 2>
val sum: list: 'T list -> 'T (requires member (+) and member Zero)
val radiation: (DateTime * float<MJ/m ^ 2>) list
val distinct: list: 'T list -> 'T list (requires equality)
val monthlyRadiation: (int * float<kWh/m ^ 2>) list
property DateTime.Month: int with get
<summary>Gets the month component of the date represented by this instance.</summary>
<returns>The month component, expressed as a value between 1 and 12.</returns>
val month: int
val days: (DateTime * float<MJ/m ^ 2>) seq
val radiationChartMJ: GoogleChart
val radiationChartKwh: GoogleChart
val radiationChartMonthly: GoogleChart
val x: float<kWh/m ^ 2>
static member Chart.Column: data: #seq<'K * 'V> seq * ?Labels: string seq * ?Options: Options -> GoogleChart (requires 'K :> key and 'V :> value)
static member Chart.Column: data: (#key * #value) seq * ?Labels: string seq * ?Options: Options -> GoogleChart
static member Chart.Column: data: #value seq * ?Labels: string seq * ?Options: Options -> GoogleChart
namespace Deedle
type WD2 =
{
date: DateTime
hourlyMin: float
hourlyMax: float
hourlyTemp: float
relativeHum: float
windSpeed: float
}
val toEnvData2: o: WD -> WD2
WD.hourlyMin: float<°C>
WD.hourlyMax: float<°C>
WD.relativeHum: float<%>
val w: float<m/s>
val nan: float
val printFrame: f: Frame<'R,'C> -> unit (requires equality and equality)
val f: Frame<'R,'C> (requires equality and equality)
Multiple items
module Frame
from Deedle
<summary>
The `Frame` module provides an F#-friendly API for working with data frames.
The module follows the usual desing for collection-processing in F#, so the
functions work well with the pipelining operator (`|>`). For example, given
a frame with two columns representing prices, we can use `Frame.pctChange` to
calculate daily returns like this:
let df = frame [ "MSFT" => prices1; "AAPL" => prices2 ]
let rets = df |> Frame.pctChange 1
rets |> Stats.mean
Note that the `Stats.mean` operation is overloaded and works both on series
(returning a number) and on frames (returning a series). You can also use
`Frame.diff` if you need absolute differences rather than relative changes.
The functions in this module are designed to be used from F#. For a C#-friendly
API, see the `FrameExtensions` type. For working with individual series, see the
`Series` module. The functions in the `Frame` module are grouped in a number of
categories and documented below.
Accessing frame data and lookup
-------------------------------
Functions in this category provide access to the values in the fame. You can
also add and remove columns from a frame (which both return a new value).
- `addCol`, `replaceCol` and `dropCol` can be used to create a new data frame
with a new column, by replacing an existing column with a new one, or by dropping
an existing column
- `cols` and `rows` return the columns or rows of a frame as a series containing
objects; `getCols` and `getRows` return a generic series and cast the values to
the type inferred from the context (columns or rows of incompatible types are skipped);
`getNumericCols` returns columns of a type convertible to `float` for convenience.
- You can get a specific row or column using `get[Col|Row]` or `lookup[Col|Row]` functions.
The `lookup` variant lets you specify lookup behavior for key matching (e.g. find the
nearest smaller key than the specified value). There are also `[try]get` and `[try]Lookup`
functions that return optional values and functions returning entire observations
(key together with the series).
- `sliceCols` and `sliceRows` return a sub-frame containing only the specified columns
or rows. Finally, `toArray2D` returns the frame data as a 2D array.
Grouping, windowing and chunking
--------------------------------
The basic grouping functions in this category can be used to group the rows of a
data frame by a specified projection or column to create a frame with hierarchical
index such as <c>Frame<'K1 * 'K2, 'C></c>. The functions always aggregate rows, so if you
want to group columns, you need to use `Frame.transpose` first.
The function `groupRowsBy` groups rows by the value of a specified column. Use
`groupRowsBy[Int|Float|String...]` if you want to specify the type of the column in
an easier way than using type inference; `groupRowsUsing` groups rows using the
specified _projection function_ and `groupRowsByIndex` projects the grouping key just
from the row index.
More advanced functions include: `aggregateRowsBy` which groups the rows by a
specified sequence of columns and aggregates each group into a single value;
`pivotTable` implements the pivoting operation [as documented in the
tutorials](../frame.html#pivot).
The `melt` and `unmelt` functions turn the data frame into a single data frame
containing columns `Row`, `Column` and `Value` containing the data of the original
frame; `unmelt` can be used to turn this representation back into an original frame.
The `stack` and `unstack` functions implement pandas-style reshape operations.
`stack` converts `Frame<'R,'C>` to a long-format `Frame<'R*'C, string>` where each
cell becomes a row keyed by `(rowKey, colKey)` with a single `"Value"` column.
`unstack` promotes the inner row-key level to column keys, producing
`Frame<'R1, 'C*'R2>` from `Frame<'R1*'R2,'C>`.
A simple windowing functions that are exposed for an entire frame operations are
`window` and `windowInto`. For more complex windowing operations, you currently have
to use `mapRows` or `mapCols` and apply windowing on individual series.
Sorting and index manipulation
------------------------------
A frame is indexed by row keys and column keys. Both of these indices can be sorted
(by the keys). A frame that is sorted allows a number of additional operations (such
as lookup using the `Lookp.ExactOrSmaller` lookup behavior). The functions in this
category provide ways for manipulating the indices. It is expected that most operations
are done on rows and so more functions are available in a row-wise way. A frame can
alwyas be transposed using `Frame.transpose`.
Index operations:
The existing row/column keys can be replaced by a sequence of new keys using the
`indexColsWith` and `indexRowsWith` functions. Row keys can also be replaced by
ordinal numbers using `indexRowsOrdinally`.
The function `indexRows` uses the specified column of the original frame as the
index. It removes the column from the resulting frame (to avoid this, use overloaded
`IndexRows` method). This function infers the type of row keys from the context, so it
is usually more convenient to use `indexRows[Date|String|Int|...]` functions. Finally,
if you want to calculate the index value based on multiple columns of the row, you
can use `indexRowsUsing`.
Sorting frame rows:
Frame rows can be sorted according to the value of a specified column using the
`sortRows` function; `sortRowsBy` takes a projection function which lets you
transform the value of a column (e.g. to project a part of the value).
The functions `sortRowsByKey` and `sortColsByKey` sort the rows or columns
using the default ordering on the key values. The result is a frame with ordered
index.
Expanding columns:
When the frame contains a series with complex .NET objects such as F# records or
C# classes, it can be useful to "expand" the column. This operation looks at the
type of the objects, gets all properties of the objects (recursively) and
generates multiple series representing the properties as columns.
The function `expandCols` expands the specified columns while `expandAllCols`
applies the expansion to all columns of the data frame.
Frame transformations
---------------------
Functions in this category perform standard transformations on data frames including
projections, filtering, taking some sub-frame of the frame, aggregating values
using scanning and so on.
Projection and filtering functions such as `[map|filter][Cols|Rows]` call the
specified function with the column or row key and an <c>ObjectSeries<'K></c> representing
the column or row. You can use functions ending with `Values` (such as `mapRowValues`)
when you do not require the row key, but only the row series; `mapRowKeys` and
`mapColKeys` can be used to transform the keys.
You can use `reduceValues` to apply a custom reduction to values of columns. Other
aggregations are available in the `Stats` module. You can also get a row with the
greaterst or smallest value of a given column using `[min|max]RowBy`.
The functions `take[Last]` and `skip[Last]` can be used to take a sub-frame of the
original source frame by skipping a specified number of rows. Note that this
does not require an ordered frame and it ignores the index - for index-based lookup
use slicing, such as `df.Rows.[lo .. hi]`, instead.
Finally the `shift` function can be used to obtain a frame with values shifted by
the specified offset. This can be used e.g. to get previous value for each key using
`Frame.shift 1 df`. The `diff` function calculates difference from previous value using
`df - (Frame.shift offs df)`.
Processing frames with exceptions
---------------------------------
The functions in this group can be used to write computations over frames that may fail.
They use the type <c>tryval<'T></c> which is defined as a discriminated union
with two cases: Success containing a value, or Error containing an exception.
Using <c>tryval<'T></c> as a value in a data frame is not generally recommended, because
the type of values cannot be tracked in the type. For this reason, it is better to use
<c>tryval<'T></c> with individual series. However, `tryValues` and `fillErrorsWith` functions
can be used to get values, or fill failed values inside an entire data frame.
The `tryMapRows` function is more useful. It can be used to write a transformation
that applies a computation (which may fail) to each row of a data frame. The resulting
series is of type <c>Series<'R, tryval<'T>></c> and can be processed using the <c>Series</c> module
functions.
Missing values
--------------
This group of functions provides a way of working with missing values in a data frame.
The category provides the following functions that can be used to fill missing values:
* `fillMissingWith` fills missing values with a specified constant
* `fillMissingUsing` calls a specified function for every missing value
* `fillMissing` and variants propagates values from previous/later keys
We use the terms _sparse_ and _dense_ to denote series that contain some missing values
or do not contain any missing values, respectively. The functions `denseCols` and
`denseRows` return a series that contains only dense columns or rows and all sparse
rows or columns are replaced with a missing value. The `dropSparseCols` and `dropSparseRows`
functions drop these missing values and return a frame with no missing values.
Joining, merging and zipping
----------------------------
The simplest way to join two frames is to use the `join` operation which can be used to
perform left, right, outer or inner join of two frames. When the row keys of the frames do
not match exactly, you can use `joinAlign` which takes an additional parameter that specifies
how to find matching key in left/right join (e.g. by taking the nearest smaller available key).
Frames that do not contian overlapping values can be combined using `merge` (when combining
just two frames) or using `mergeAll` (for larger number of frames). Tha latter is optimized
to work well for a large number of data frames.
Finally, frames with overlapping values can be combined using `zip`. It takes a function
that is used to combine the overlapping values. A `zipAlign` function provides a variant
with more flexible row key matching (as in `joinAlign`)
Hierarchical index operations
-----------------------------
A data frame has a hierarchical row index if the row index is formed by a tuple, such as
<c>Frame<'R1 * 'R2, 'C></c>. Frames of this kind are returned, for example, by the grouping
functions such as <c>Frame.groupRowsBy</c>. The functions in this category provide ways for
working with data frames that have hierarchical row keys.
The functions <c>applyLevel</c> and <c>reduceLevel</c> can be used to reduce values according to
one of the levels. The <c>applyLevel</c> function takes a reduction of type <c>Series<'K, 'T> -> 'T</c>
while <c>reduceLevel</c> reduces individual values using a function of type <c>'T -> 'T -> 'T</c>.
The functions <c>nest</c> and <c>unnest</c> can be used to convert between frames with
hierarchical indices (<c>Frame<'K1 * 'K2, 'C></c>) and series of frames that represent
individual groups (<c>Series<'K1, Frame<'K2, 'C>></c>). The <c>nestBy</c> function can be
used to perform group by operation and return the result as a series of frems.
</summary>
<category>Frame and series operations</category>
--------------------
type Frame =
static member ReadCsv: location: string * hasHeaders: Nullable<bool> * inferTypes: Nullable<bool> * inferRows: Nullable<int> * schema: string * separators: string * culture: string * maxRows: Nullable<int> * missingValues: string array * preferOptions: bool * encoding: Encoding -> Frame<int,string> + 1 overload
static member ReadReader: reader: IDataReader -> Frame<int,string>
static member CustomExpanders: Dictionary<Type,Func<obj,(string * Type * obj) seq>>
static member NonExpandableInterfaces: ResizeArray<Type>
static member NonExpandableTypes: HashSet<Type>
<summary>
Provides static methods for creating frames, reading frame data
from CSV files and database (via IDataReader). The type also provides
global configuration for reflection-based expansion.
</summary>
<category>Frame and series operations</category>
--------------------
type Frame<'TRowKey,'TColumnKey (requires equality and equality)> =
interface IDynamicMetaObjectProvider
interface INotifyCollectionChanged
interface IFrameFormattable
interface IFsiFormattable
interface IFrame
new: rowIndex: IIndex<'TRowKey> * columnIndex: IIndex<'TColumnKey> * data: IVector<IVector> * indexBuilder: IIndexBuilder * vectorBuilder: IVectorBuilder -> Frame<'TRowKey,'TColumnKey> + 1 overload
member AddColumn: column: 'TColumnKey * series: 'V seq -> unit + 3 overloads
member AggregateRowsBy: groupBy: 'TColumnKey seq * aggBy: 'TColumnKey seq * aggFunc: Func<Series<'TRowKey,'a>,'b> -> Frame<int,'TColumnKey>
member Clone: unit -> Frame<'TRowKey,'TColumnKey>
member ColumnApply: f: Func<Series<'TRowKey,'T>,ISeries<'TRowKey>> -> Frame<'TRowKey,'TColumnKey> + 1 overload
...
<summary>
A frame is the key Deedle data structure (together with series). It represents a
data table (think spreadsheet or CSV file) with multiple rows and columns. The frame
consists of row index, column index and data. The indices are used for efficient
lookup when accessing data by the row key `'TRowKey` or by the column key
`'TColumnKey`. Deedle frames are optimized for the scenario when all values in a given
column are of the same type (but types of different columns can differ).
</summary>
<remarks><para>Joining, zipping and appending:</para><para>
More info
</para></remarks>
<category>Core frame and series types</category>
--------------------
new: names: 'TColumnKey seq * columns: ISeries<'TRowKey> seq -> Frame<'TRowKey,'TColumnKey>
new: rowIndex: Indices.IIndex<'TRowKey> * columnIndex: Indices.IIndex<'TColumnKey> * data: IVector<IVector> * indexBuilder: Indices.IIndexBuilder * vectorBuilder: Vectors.IVectorBuilder -> Frame<'TRowKey,'TColumnKey>
'R
'C
val saved: Globalization.CultureInfo
namespace System.Globalization
Multiple items
type CultureInfo =
interface ICloneable
interface IFormatProvider
new: culture: int -> unit + 3 overloads
member ClearCachedData: unit -> unit
member Clone: unit -> obj
member Equals: value: obj -> bool
member GetConsoleFallbackUICulture: unit -> CultureInfo
member GetFormat: formatType: Type -> obj
member GetHashCode: unit -> int
member ToString: unit -> string
...
<summary>Provides information about a specific culture (called a locale for unmanaged code development). The information includes the names for the culture, the writing system, the calendar used, the sort order of strings, and formatting for dates and numbers.</summary>
--------------------
Globalization.CultureInfo(culture: int) : Globalization.CultureInfo
Globalization.CultureInfo(name: string) : Globalization.CultureInfo
Globalization.CultureInfo(culture: int, useUserOverride: bool) : Globalization.CultureInfo
Globalization.CultureInfo(name: string, useUserOverride: bool) : Globalization.CultureInfo
property Globalization.CultureInfo.CurrentCulture: Globalization.CultureInfo with get, set
<summary>Gets or sets the <see cref="T:System.Globalization.CultureInfo" /> object that represents the culture used by the current thread and task-based asynchronous operations.</summary>
<exception cref="T:System.ArgumentNullException">The property is set to <see langword="null" />.</exception>
<returns>The culture used by the current thread and task-based asynchronous operations.</returns>
property Globalization.CultureInfo.InvariantCulture: Globalization.CultureInfo with get
<summary>Gets the <see cref="T:System.Globalization.CultureInfo" /> object that is culture-independent (invariant).</summary>
<returns>The object that is culture-independent (invariant).</returns>
static member FrameExtensions.Print: frame: Frame<'K,'V> -> unit (requires equality and equality)
static member FrameExtensions.Print: frame: Frame<'K,'V> * printTypes: bool -> unit (requires equality and equality)
val dataFrame: Frame<DateTime,string>
static member Frame.ofRecords: series: Series<'K,'R> -> Frame<'K,string> (requires equality)
static member Frame.ofRecords: values: 'T seq -> Frame<int,string>
static member Frame.ofRecords: values: Collections.IEnumerable * indexCol: string -> Frame<'R,string> (requires equality)
val indexRowsDateTime: column: 'C -> frame: Frame<'R1,'C> -> Frame<DateTime,'C> (requires equality and equality)
<summary>
Returns a data frame whose rows are indexed based on the specified column of the original
data frame. This function casts (or converts) the column key to values of type `DateTime`
(a generic variant that may require some type annotation is `Frame.indexRows`)
The specified column is removed from the resulting frame.
</summary>
<param name="frame">Source data frame whose row index is to be replaced.</param>
<param name="column">The name of a column in the original data frame that will be used for the new index. Note that the values in the column need to be unique.</param>
<category>Sorting and index manipulation</category>
val meanTemp: float
type Stats =
static member corr: series1: Series<'K,'V1> -> series2: Series<'K,'V2> -> float (requires equality)
static member corrFrame: frame: Frame<'R,'C> -> Frame<'C,'C> (requires equality and equality)
static member count: series: Series<'K,'V> -> int (requires equality) + 1 overload
static member cov: series1: Series<'K,'V1> -> series2: Series<'K,'V2> -> float (requires equality)
static member covFrame: frame: Frame<'R,'C> -> Frame<'C,'C> (requires equality and equality)
static member describe: series: Series<'K,'V> -> Series<string,float> (requires equality and equality) + 1 overload
static member expandingCount: series: Series<'K,'V> -> Series<'K,float> (requires equality)
static member expandingKurt: series: Series<'K,'V> -> Series<'K,float> (requires equality)
static member expandingMax: series: Series<'K,'V> -> Series<'K,float> (requires equality)
static member expandingMean: series: Series<'K,'V> -> Series<'K,float> (requires equality)
...
static member Stats.mean: frame: Frame<'R,'C> -> Series<'C,float> (requires equality and equality)
static member Stats.mean: series: Series<'K,'V> -> float (requires equality)
val meanWindOfFrame: float
val noMissingValues: Frame<DateTime,string>
property Frame.RowsDense: RowSeries<DateTime,string> with get
<category>Accessors and slicing</category>
Multiple items
module Series
from Deedle
<summary>
The `Series` module provides an F#-friendly API for working with data and time series.
The API follows the usual design for collection-processing in F#, so the functions work
well with the pipelining (<c>|></c>) operator. For example, given a series with ages,
we can use `Series.filterValues` to filter outliers and then `Stats.mean` to calculate
the mean:
ages
|> Series.filterValues (fun v -> v > 0.0 && v < 120.0)
|> Stats.mean
The module provides comprehensive set of functions for working with series. The same
API is also exposed using C#-friendly extension methods. In C#, the above snippet could
be written as:
[lang=csharp]
ages
.Where(kvp => kvp.Value > 0.0 && kvp.Value < 120.0)
.Mean()
For more information about similar frame-manipulation functions, see the `Frame` module.
For more information about C#-friendly extensions, see `SeriesExtensions`. The functions
in the `Series` module are grouped in a number of categories and documented below.
Accessing series data and lookup
--------------------------------
Functions in this category provide access to the values in the series.
- The term _observation_ is used for a key value pair in the series.
- When working with a sorted series, it is possible to perform lookup using
keys that are not present in the series - you can specify to search for the
previous or next available value using _lookup behavior_.
- Functions such as `get` and `getAll` have their counterparts `lookup` and
`lookupAll` that let you specify lookup behavior.
- For most of the functions that may fail, there is a `try[Foo]` variant that
returns `None` instead of failing.
- Functions with a name ending with `At` perform lookup based on the absolute
integer offset (and ignore the keys of the series)
Series transformations
----------------------
Functions in this category perform standard transformations on series including
projections, filtering, taking some sub-series of the series, aggregating values
using scanning and so on.
Projection and filtering functions generally skip over missing values, but there
are variants `filterAll` and `mapAll` that let you handle missing values explicitly.
Keys can be transformed using `mapKeys`. When you do not need to consider the keys,
and only care about values, use `filterValues` and `mapValues` (which is also aliased
as the `$` operator).
Series supports standard set of folding functions including `reduce` and `fold` (to
reduce series values into a single value) as well as the `scan[All]` function, which
can be used to fold values of a series into a series of intermeidate folding results.
The functions `take[Last]` and `skip[Last]` can be used to take a sub-series of the
original source series by skipping a specified number of elements. Note that this
does not require an ordered series and it ignores the index - for index-based lookup
use slicing, such as `series.[lo .. hi]`, instead.
Finally the `shift` function can be used to obtain a series with values shifted by
the specified offset. This can be used e.g. to get previous value for each key using
`Series.shift 1 ts`. The `diff` function calculates difference from previous value using
`ts - (Series.shift offs ts)`.
Processing series with exceptions
---------------------------------
The functions in this group can be used to write computations over series that may fail.
They use the type <c>tryval<'T></c> which is defined as a discriminated union
with two cases: Success containing a value, or Error containing an exception.
The function `tryMap` lets you create <c>Series<'K, tryval<'T>></c> by mapping over values
of an original series. You can then extract values using `tryValues`, which throws
`AggregateException` if there were any errors. Functions `tryErrors` and `trySuccesses`
give series containing only errors and successes. You can fill failed values with
a constant using `fillErrorsWith`.
Hierarchical index operations
-----------------------------
When the key of a series is tuple, the elements of the tuple can be treated
as multiple levels of a index. For example <c>Series<'K1 * 'K2, 'V></c> has two
levels with keys of types <c>'K1</c> and <c>'K2</c> respectively.
The functions in this cateogry provide a way for aggregating values in the
series at one of the levels. For example, given a series `input` indexed by
two-element tuple, you can calculate mean for different first-level values as
follows:
input |> applyLevel fst Stats.mean
Note that the `Stats` module provides helpers for typical statistical operations,
so the above could be written just as `input |> Stats.levelMean fst`.
Grouping, windowing and chunking
--------------------------------
This category includes functions that group data from a series in some way. Two key
concepts here are _window_ and _chunk_. Window refers to (overlapping) sliding windows
over the input series while chunk refers to non-overlapping blocks of the series.
The boundary behavior can be specified using the `Boundary` flags. The value
`Skip` means that boundaries (incomplete windows or chunks) should be skipped. The value
`AtBeginning` and `AtEnding` can be used to define at which side should the boundary be
returned (or skipped). For chunking, `AtBeginning ||| Skip` makes sense and it means that
the incomplete chunk at the beginning should be skipped (aligning the last chunk with the end).
The behavior may be specified in a number of ways (which is reflected in the name):
- `dist` - using an absolute distance between the keys
- `while` - using a condition on the first and last key
- `size` - by specifying the absolute size of the window/chunk
The functions ending with `Into` take a function to be applied to the window/chunk.
The functions `window`, `windowInto` and `chunk`, `chunkInto` are simplified versions
that take a size. There is also `pairwise` function for sliding window of size two.
Missing values
--------------
This group of functions provides a way of working with missing values in a series.
The `dropMissing` function drops all keys for which there are no values in the series.
The `withMissingFrom` function lets you copy missing values from another series.
The remaining functions provide different mechanism for filling the missing values.
* `fillMissingWith` fills missing values with a specified constant
* `fillMissingUsing` calls a specified function for every missing value
* `fillMissing` and variants propagates values from previous/later keys
Sorting and index manipulation
------------------------------
A series that is sorted by keys allows a number of additional operations (such as lookup
using the `Lookp.ExactOrSmaller` lookup behavior). However, it is also possible to sort
series based on the values - although the functions for manipulation with series do not
guarantee that the order will be preserved.
To sort series by keys, use `sortByKey`. Other sorting functions let you sort the series
using a specified comparer function (`sortWith`), using a projection function (`sortBy`)
and using the default comparison (`sort`).
In addition, you can also replace the keys of a series with other keys using `indexWith`
or with integers using `indexOrdinally`. To pick and reorder series values using to match
a list of keys use `realign`.
Sampling, resampling and advanced lookup
----------------------------------------
Given a (typically) time series sampling or resampling makes it possible to
get time series with representative values at lower or uniform frequency.
We use the following terminology:
- `lookup` and `sample` functions find values at specified key; if a key is not
available, they can look for value associated with the nearest smaller or
the nearest greater key.
- `resample` function aggregate values values into chunks based
on a specified collection of keys (e.g. explicitly provided times), or
based on some relation between keys (e.g. date times having the same date).
- `resampleUniform` is similar to resampling, but we specify keys by
providing functions that generate a uniform sequence of keys (e.g. days),
the operation also fills value for days that have no corresponding
observations in the input sequence.
Joining, merging and zipping
----------------------------
Given two series, there are two ways to combine the values. If the keys in the series
are not overlapping (or you want to throw away values from one or the other series),
then you can use `merge` or `mergeUsing`. To merge more than 2 series efficiently, use
the `mergeAll` function, which has been optimized for large number of series.
If you want to align two series, you can use the _zipping_ operation. This aligns
two series based on their keys and gives you tuples of values. The default behavior
(`zip`) uses outer join and exact matching. For ordered series, you can specify
other forms of key lookups (e.g. find the greatest smaller key) using `zipAlign`.
functions ending with `Into` are generally easier to use as they call a specified
function to turn the tuple (of possibly missing values) into a new value.
For more complicated behaviors, it is often convenient to use joins on frames instead
of working with series. Create two frames with single columns and then use the join
operation. The result will be a frame with two columns (which is easier to use than
series of tuples).
</summary>
<category>Frame and series operations</category>
--------------------
type Series =
static member ofNullables: values: Nullable<'a> seq -> Series<int,'a> (requires default constructor and value type and 'a :> ValueType)
static member ofObservations: observations: ('a * 'b) seq -> Series<'a,'b> (requires equality)
static member ofOptionalObservations: observations: ('K * 'a option) seq -> Series<'K,'a> (requires equality)
static member ofValues: values: 'a seq -> Series<int,'a>
--------------------
type Series<'K,'V (requires equality)> =
interface ISeriesFormattable
interface IFsiFormattable
interface ISeries<'K>
new: index: IIndex<'K> * vector: IVector<'V> * vectorBuilder: IVectorBuilder * indexBuilder: IIndexBuilder -> Series<'K,'V> + 3 overloads
member After: lowerExclusive: 'K -> Series<'K,'V>
member Aggregate: aggregation: Aggregation<'K> * keySelector: Func<DataSegment<Series<'K,'V>>,'TNewKey> * valueSelector: Func<DataSegment<Series<'K,'V>>,OptionalValue<'R>> -> Series<'TNewKey,'R> (requires equality) + 1 overload
member AsyncMaterialize: unit -> Async<Series<'K,'V>>
member Before: upperExclusive: 'K -> Series<'K,'V>
member Between: lowerInclusive: 'K * upperInclusive: 'K -> Series<'K,'V>
member Compare: another: Series<'K,'V> -> Series<'K,Diff<'V>>
...
<summary>
The type <c>Series<K, V></c> represents a data series consisting of values `V` indexed by
keys `K`. The keys of a series may or may not be ordered
</summary>
<category>Core frame and series types</category>
--------------------
new: pairs: Collections.Generic.KeyValuePair<'K,'V> seq -> Series<'K,'V>
new: keys: 'K seq * values: 'V seq -> Series<'K,'V>
new: keys: 'K array * values: 'V array -> Series<'K,'V>
new: index: Indices.IIndex<'K> * vector: IVector<'V> * vectorBuilder: Vectors.IVectorBuilder * indexBuilder: Indices.IIndexBuilder -> Series<'K,'V>
val dropMissing: series: Series<'K,'T> -> Series<'K,'T> (requires equality)
<summary>
Drop missing values from the specified series. The returned series contains
only those keys for which there is a value available in the original one.
</summary>
<param name="series">An input series to be filtered</param>
<example><code>
let s = series [ 1 => 1.0; 2 => Double.NaN ]
s |> Series.dropMissing
// val it : Series<int,float> = series [ 1 => 1]
</code></example>
<category>Missing values</category>
static member Frame.ofRows: rows: ('R * #ISeries<'C>) seq -> Frame<'R,'C> (requires equality and equality)
static member Frame.ofRows: rows: Series<'R,#ISeries<'C>> -> Frame<'R,'C> (requires equality and equality)
val dailyMeans: Frame<int,string>
val groupRowsUsing: selector: ('R -> ObjectSeries<'C> -> 'K) -> frame: Frame<'R,'C> -> Frame<('K * 'R),'C> (requires equality and equality and equality)
<summary>
Group rows of a data frame using the specified `selector`. The selector is called with
a row key and object series representing the row and should return a new key. The result
is a frame with multi-level index, where the first level is formed by the newly created
keys.
</summary>
<category>Grouping, windowing and chunking</category>
val time: DateTime
val getNumericCols: frame: Frame<'R,'C> -> Series<'C,Series<'R,float>> (requires equality and equality)
<summary>
Returns a series of columns of the data frame indexed by the column keys,
which contains those series whose values are convertible to float, and with
missing values where the conversion fails.
</summary>
<category>Accessing frame data and lookup</category>
val mapValues: f: ('T -> 'R) -> series: Series<'K,'T> -> Series<'K,'R> (requires equality)
<summary>
Returns a new series whose values are the results of applying the given function to
values of the original series. This function skips over missing values and call the
function with just values. It is also aliased using the `$` operator so you can write
`series $ func` for `series |> Series.mapValues func`.
</summary>
<category>Series transformations</category>
static member Stats.levelMean: level: ('K -> 'L) -> series: Series<'K,'V> -> Series<'L,float> (requires equality and equality)
val fst: tuple: ('T1 * 'T2) -> 'T1
static member Frame.ofColumns: cols: Series<'C,#ISeries<'R>> -> Frame<'R,'C> (requires equality and equality)
static member Frame.ofColumns: cols: ('C * #ISeries<'R>) seq -> Frame<'R,'C> (requires equality and equality)
val monthFrame: Frame<DateTime,string>
val dailyMeansOfMonth: Frame<int,string>
val euroCountries: WorldBankData.ServiceTypes.Region
property WorldBankData.ServiceTypes.WorldBankDataService.Regions: WorldBankData.ServiceTypes.Regions with get
val unemployment: Frame<int,string>
val c: WorldBankData.ServiceTypes.Country
property WorldBankData.ServiceTypes.Region.Countries: WorldBankData.ServiceTypes.Countries with get
<summary>The indicators for the region</summary>
val series: observations: ('a * 'b) seq -> Series<'a,'b> (requires equality)
<summary>
Create a series from a sequence of key-value pairs that represent
the observations of the series. This function can be used together
with the `=>` operator to create key-value pairs.
</summary>
<example>
// Creates a series with squares of numbers
let sqs = series [ 1 => 1.0; 2 => 4.0; 3 => 9.0 ]
</example>
val frame: columns: ('a * #ISeries<'c>) seq -> Frame<'c,'a> (requires equality and equality)
<summary>
A function for constructing data frame from a sequence of name - column pairs.
This provides a nicer syntactic sugar for `Frame.ofColumns`.
</summary>
<example>
To create a simple frame with two columns, you can write:
<code>
frame [ "A" => series [ 1 => 30.0; 2 => 35.0 ]
"B" => series [ 1 => 30.0; 3 => 40.0 ] ]
</code></example>
<category>Frame construction</category>
val recent: Frame<int,string>
property Frame.Rows: RowSeries<int,string> with get
<category>Accessors and slicing</category>
val highestUnemployment: Series<string,float>
val sort: series: Series<'K,'V> -> Series<'K,'V> (requires equality and comparison)
<summary>
Returns a new series, containing the observations of the original series sorted based
on the default ordering defined on the values of the series.
</summary>
<category>Sorting and index manipulation</category>
val rev: series: Series<'K,'T> -> Series<'K,'T> (requires equality)
<summary>
Returns a new series, containing the observations of the original series in a reverse order.
</summary>
<category>Sorting and index manipulation</category>
val take: count: int -> series: Series<'K,'T> -> Series<'K,'T> (requires equality)
<summary>
Returns a series that contains the specified number of keys from the original series.
</summary>
<param name="count">Number of keys to take; must be smaller or equal to the original number of keys</param>
<param name="series">Input series from which the keys are taken</param>
<category>Series transformations</category>
val round: value: 'T -> 'T (requires member Round)
namespace MathNet
namespace MathNet.Numerics
namespace MathNet.Numerics.LinearAlgebra
val unemploymentMat: Matrix<float>
val fillMissingWith: value: 'T -> frame: Frame<'R,'C> -> Frame<'R,'C> (requires equality and equality)
<summary>
Fill missing values of a given type in the frame with a constant value.
The fill value is applied to columns whose element type matches the fill value type
(using safe numeric widening). This includes both cases where the column type can be
widened to the fill value type (e.g. decimal columns filled with a float value) and
cases where the fill value can be widened to the column type (e.g. an integer fill
value filling float columns).
Columns whose element type is incompatible with the fill value type are left unchanged.
</summary>
<param name="frame">An input data frame that is to be filled</param>
<param name="value">A constant value that is used to fill all missing values</param>
<category>Missing values</category>
val toArray2D: frame: Frame<'R,'C> -> float array2d (requires equality and equality)
<summary>
Returns data of the data frame as a 2D array containing data as `float` values.
Missing data are represented as `Double.NaN` in the returned array.
<category>Accessing frame data and lookup</category>
</summary>
type Matrix<'T (requires default constructor and value type and 'T :> IEquatable<'T> and 'T :> IFormattable and 'T :> ValueType)> =
interface IFormattable
interface IEquatable<Matrix<'T>>
interface ICloneable
member Add: scalar: 'T -> Matrix<'T> + 3 overloads
member Append: right: Matrix<'T> -> Matrix<'T> + 1 overload
member AsArray: unit -> 'T array2d
member AsColumnArrays: unit -> 'T array array
member AsColumnMajorArray: unit -> 'T array
member AsRowArrays: unit -> 'T array array
member AsRowMajorArray: unit -> 'T array
...
<summary>
Defines the base class for <c>Matrix</c> classes.
</summary>
<summary>
Defines the base class for <c>Matrix</c> classes.
</summary>
<typeparam name="T">Supported data types are <c>double</c>, <c>single</c>, <see cref="N:MathNet.Numerics.LinearAlgebra.Complex" />, and <see cref="N:MathNet.Numerics.LinearAlgebra.Complex32" />.</typeparam>
<summary>
Defines the base class for <c>Matrix</c> classes.
</summary>
<summary>
Defines the base class for <c>Matrix</c> classes.
</summary>
val avgVect: Vector<float>
val fillMissingWith: value: 'a -> series: Series<'K,'T> -> Series<'K,'T> (requires equality)
<summary>
Fill missing values in the series with a constant value.
</summary>
<param name="series">An input series that is to be filled</param>
<param name="value">A constant value that is used to fill all missing values</param>
<category>Missing values</category>
val values: series: Series<'K,'T> -> 'T seq (requires equality)
<summary>
Returns the (non-missing) values of the series as a sequence
</summary>
<category>Accessing series data and lookup</category>
Multiple items
type Vector =
static member ofOptionalValues: data: 'T option seq -> IVector<'T> + 2 overloads
static member ofValues: data: 'T array -> IVector<'T> + 1 overload
<summary>
Type that provides a simple access to creating vectors represented
using the built-in `ArrayVector` type that stores the data in a
continuous block of memory.
</summary>
--------------------
type Vector<'T (requires default constructor and value type and 'T :> IEquatable<'T> and 'T :> IFormattable and 'T :> ValueType)> =
interface IFormattable
interface IEquatable<Vector<'T>>
interface IList
interface ICollection
interface IEnumerable
interface IList<'T>
interface ICollection<'T>
interface seq<'T>
interface ICloneable
override AbsoluteMaximum: unit -> 'T
...
<summary>
Defines the generic class for <c>Vector</c> classes.
</summary>
<typeparam name="T">Supported data types are double, single, <see cref="N:MathNet.Numerics.LinearAlgebra.Complex" />, and <see cref="N:MathNet.Numerics.LinearAlgebra.Complex32" />.</typeparam>
val weighted: Vector<float>
namespace Microsoft.FSharp.Quotations
module Patterns
from Microsoft.FSharp.Quotations
module DerivedPatterns
from Microsoft.FSharp.Quotations
val quoted: Expr<int>
val quotedText: string
val sprintf: format: Printf.StringFormat<'T> -> 'T
val show: e: Expr -> string
val e: Expr
Multiple items
type Expr =
member GetFreeVars: unit -> Var seq
member Substitute: substitution: (Var -> Expr option) -> Expr
member ToString: full: bool -> string
static member AddressOf: target: Expr -> Expr
static member AddressSet: target: Expr * value: Expr -> Expr
static member Application: functionExpr: Expr * argument: Expr -> Expr
static member Applications: functionExpr: Expr * arguments: Expr list list -> Expr
static member Call: methodInfo: MethodInfo * arguments: Expr list -> Expr + 1 overload
static member CallWithWitnesses: methodInfo: MethodInfo * methodInfoWithWitnesses: MethodInfo * witnesses: Expr list * arguments: Expr list -> Expr + 1 overload
static member Cast: source: Expr -> Expr<'T>
...
--------------------
type Expr<'T> =
inherit Expr
member Raw: Expr
active recognizer SpecificCall: Expr -> Expr -> (Expr option * Type list * Expr list) option
val l: Expr
val r: Expr
active recognizer Value: Expr -> (objnull * Type) option
val v: objnull
val eval: e: Expr -> int
val unbox: value: objnull -> 'T
val failwith: message: string -> 'T
val shown: string
val evaluated: int
val direct: int
val twice: e: Expr<int> -> Expr<int>
val e: Expr<int>
val generated: string
val generatedValue: int
val numbers: int list
val large: int list
val query: Linq.QueryBuilder
val n: int
custom operation: where (bool)
Calls Linq.QueryBuilder.Where
custom operation: sortBy ('Key)
Calls Linq.QueryBuilder.SortBy
custom operation: select ('Result)
Calls Linq.QueryBuilder.Select