Modeling domain type - f#

A limit price has a decimal value. A Market price does not.
How do I model this in F#?
module TradingDomain
let NoPrice = None
type PriceActionType =
| Limit of decimal
| Market of NoPrice

You can just not give Market any arguments:
type PriceActionType =
| Limit of decimal
| Market

There are a couple of ways to go about it, but if you do domain modelling it's a good idea to have an understanding of all the components, in this case, 1) how traders think about the order, 2) how FIX (if that's what's being used) thinks about the order, and 3) how the market you trade thinks about the order. Btw, there's this book that you might find useful. Also, Chapter 7 in F# Deep Dives.
That said Tarmil's answer should work for you, and here but I have two comments. Sometimes it's better to be explicit about the type and use .NET types. float and decimal are F# aliases and they might refer to the function that casts to float. There is also the possibility to use Some and None for expressing the price. So here's a version that includes the orderside as well:
type Price =
| Limit of Decimal
| Market
type OrderSide =
| Buy of Price
| Sell of Price
| ShortSell of Price
You can use it like this: Buy (Limit 10.0M) or Sell Market.
You could also define Price like this:
type Price2 =
| Limit of Decimal option
| None
Whichever version will help you later do validation.

Related

F# why is cast needed?

I'm new to F# and working through this article. In this article there is a sample of the following recursive type:
type Book = {title: string; price: decimal}
type ChocolateType = Dark | Milk | SeventyPercent
type Chocolate = {chocType: ChocolateType ; price: decimal}
type WrappingPaperStyle =
| HappyBirthday
| HappyHolidays
| SolidColor
type Gift =
| Book of Book
| Chocolate of Chocolate
| Wrapped of Gift * WrappingPaperStyle
| Boxed of Gift
| WithACard of Gift * message:string
Which is used in the following way:
let wolfHall = {title="Wolf Hall"; price=20m}
let birthdayPresent = WithACard (Wrapped (Book wolfHall, HappyBirthday), "Happy Birthday")
What I don't understand: Why do I need to cast wolfHall to a Book? The compiler should know that wolfHall is a Book, and therefore a Gift, based on the beforehand let-assignment.
Thanks
In your code, Book means two things:
It's the name of the record type with two fields, title and price.
It's one of the cases of the discriminated union Gift. This particular case is of type Book (the record type), and it's named Book. It doesn't have to be named the same, but it can be (and often is - the same is true of the next case, Chocolate).
So, you're not casting wolfHall. You're constructing an instance of Gift, using the particular case constructor which happens to be named the same as the type it wraps. The compiler knows the difference and usually when you're reading the code, you can tell the difference. But if it's confusing, you can certainly name that constructor something else.

What is the correct designation for values of discriminated union types?

Consider this type definition:
type ChoiceOne =
| A
| B
and this binding
let c1 = A
I assume the correct way to translate this into natural language would be "the value A of type ChoiceOne is constructed and bound to the name c1".
Now take a look at this next type definition and binding:
type ChoiceTwo =
| A of int
| B of float
let c1 = A 1
I now see several ways of describing what is going on here:
"the value A of type ChoiceTwo is constructed ..." ( and what about the 1 ? )
"the value 1 of type ChoiceTwo is constructed ..." ( and what about the A ? )
"the value A of type ChoiceTwo with the ( inner value ? associated value ? ... ) 1 is constructed ..."
I guess option 3 describes the situation best, but how can I correctly designate the value 1 with respect to the (other?) value A of type ChoiceTwo ?
Here's the terminology that I use, which I believe is widely accepted, using my own example:
type MyDU =
| A of int
| B
A is a case
A is also a function that takes an int and returns a value of type MyDU
Therefore, A 1 is a value of type MyDU
B is a case
B is also a value of type MyDU
The only words needed here are "case", "value", "function" and "type". Don't use the word "construct". In general, when talking about F# code, if you can accurately replace any words that you use with the ones that I recommend, then do so!
This is all splitting hairs. Nobody really cares about how exactly to say these things outside of a quiz in college, and even then, I would recommend maybe transferring to a different college :-)
But if you really want to split hairs, here we go.
In your very first example, the value A is not "constructed". Since it doesn't have parameters, there can be only one instance of it, and that instance always exists, so there is no need to "construct" it.
To be sure, A may still be referred to as a "constructor", but it's also a "value" at the same time.
In the second example, it is sometimes said that "a value A 1 was constructed", but more often "a value A constructed with parameter 1"

F# Sequences and Records

I have 2 sequences...
type Suit = Spades | Clubs | Hearts | Diamonds
type Rank = Ace | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King
type Card = { suit: Suit; rank: Rank}
and intValueCard = {rank: Rank; value: int} // translates the union into an actual int
and just wondering how I can get the Card's Rank in an actual int... so far I have
let getActualValue (card:Card) =
value |> translatedValue.Rank
but for the life of me I can't figure out how to deal with a sequence and getActualValue doesn't work..
I don't see any sequences. You have Suit and Rank which are discriminated unions, and you have Card which is a record. Not sure what you meant by intValueCard = {rank: Rank; value: int}, and getActualValue refers to a translatedValue which isn't explained. What will the integer value from the rank be used for? You can possibly get better help if you edit and improve your question.
Let's assume you want the rank in order to calculate the advantage in a game. It is probably best to create a function like this.
let weightFromRank rank =
match rank with
| Ace -> 1
| Two -> 2
...etc...
You can use the function keyword to make a less verbose version of this function.
I believe it is not a good idea to use an enum, because you will miss out on important advantages of functional programming. Enum is a .NET type, and not a functional type.
Different kinds of games have different kind of weights on Ace. Some games give Ace a weight of 14, one above the King. You can then have different functions for calculating the weight, depending on what kind of game is played.
Take the following advice with a grain of salt, since I'm not a top notch expert on F#. A different approach would be to put the weight as a separate field in a record or a discriminated union or something like that. This approach I believe is less efficient, because the weight follows from the rank, so you would effectively be duplicating information in places where it's not needed, thereby also making your code more difficult to understand. It would also be less efficient to handle different weights for different kinds of games.
You can declare Rank as a enum:
type Rank =
| Ace = 1
| Two = 2
| Three = 3
....
then use int to get the underlying value:
let getActualValue ({rank = r}) = int r
If you want the integer rank for comparison with other ranks, then you can just compare the discriminated union values instead, as comparison is built into them for free:
Eight < Nine // true
Jack < Six // false
[Seven; Ace; Four; Two] |> List.sort
// [Ace; Two; Four; Seven]
Now, if you really need the integer rank value for some reason you could use reflection to get the DU cases. Just make sure that you that you do it inside a top level module value, not inside a function, so that the reflection is only done once when the program starts:
open FSharp.Reflection
let ranks =
FSharpType.GetUnionCases(typeof<Rank>)
|> Array.map (fun c -> FSharpValue.MakeUnion(c, [||]) :?> Rank)
let getActualValue rank = Array.findIndex ((=) rank) ranks
getActualValue Ace // 0
getActualValue Two // 1
getActualValue King // 12

Using F# Units Of Measure to calculate a gross from a net amount + a vat amount

I've recently started playing around with Units Of Measure in F# and thought I could write a very simple example that calculates a gross amount given a VAT rate and a net total.
For instance:
The net amount might equal 600.00
The VAT rate would be 20%
Which should give a Gross amount of 720.00
I have the following types
[<Measure>] type net
[<Measure>] type vatRate
[<Measure>] type vatValue = net * vatRate
[<Measure>] type gross
And the following functions
let calculateVat (netValue : float<net>) (vat : float<vatRate>) = netValue * vat
let calculateGross (netValue : float<net>) (vat : float<vatValue>) = netValue + vat
With the following tests:
let calcVatTest = calculateVat 600.00<net> 0.2<vatRate> = 120.00<vatValue>
let calcGrossTest = calculateGross 600.00<net> 120.00<vatValue> = 720.00<gross>
The problem I'm having is that I can't get the correct syntax for the calculateGross function and I'm getting a compilation error:
"The unit of measure 'vatValue' does not match the unit of measure 'net'"
It seems as though I need to define gross similar to the following:
[<Measure>] type gross = net + vatValue
But the compiler doesn't like the +
Any ideas how I might achieve this?
Thanks
Only operators *, /, and ^ are supported in measure expressions—although - may be used to construct a negative exponent. Logically, this makes sense because in order to use dimensional analysis, the compiler has to consider each factor to consist of a scalar and a single units or a product of units.
Honestly, this doesn't seem to be a good use for units of measure. It looks like it just complicates your code without providing too much more expressiveness.
Further reading
Units of Measure (F#)
I know you didn't ask but this is too big a point to pass up and this is too much to put into a comment. I think probably you don't want the unit of measure for gross, vatRate etc because I'd expect gross, net and so forth to be in terms of currency.
Something more like this (assuming the VAT is a percent of a European currency):
[<Measure>] type euro
[<Measure>] type percent
let gross = 100.0<euro>
let vatRate = 5.0<percent>
I mean to say that I think you've gotten hold of the wrong way to use units of measure. Gross isn't a unit of measure--it's a number; likewise vatRate.
In your sample, the problem is that you are trying to add two things with different units (price without VAT and VAT value) - that's not allowed by the static typing - you can only add things of the same unit (which is part of the principles behind units of measure - there is not much you can do about this).
I think that the most natural solution (that, however, does not give you as strong safety guarantees) would be to make the VAT rate dimensionless number.
In general (when thinking about the physical meaning), rates are examples of number that does not have a unit - rate is generally calculated as X<unit> / Y<unit> for some numbers X and Y of the same unit and so the unit cancels out during the division.
So you could write something like this:
[<Measure>] type net
[<Measure>] type vatRate = 1
[<Measure>] type vatValue = net * vatRate
let calculateVat (netValue : float<net>) (vat : float<vatRate>) = netValue * vat
let calculateGross (netValue : float<net>) (vat : float<vatValue>) = netValue + vat
This means that float<vatRate> will really be just ordinary float and vatValue is the same as net (but you can still use the aliases in your code as a documentation).
So, this removes the distinction between price with VAT and price without VAT, but at least your program still statically distinguishes between float representing money and float representing just numbers.

Multiset Partition Using Linear Arithmetic and Z3

I have to partition a multiset into two sets who sums are equal. For example, given the multiset:
1 3 5 1 3 -1 2 0
I would output the two sets:
1) 1 3 3
2) 5 -1 2 1 0
both of which sum to 7.
I need to do this using Z3 (smt2 input format) and "Linear Arithmetic Logic", which is defined as:
formula : formula /\ formula | (formula) | atom
atom : sum op sum
op : = | <= | <
sum : term | sum + term
term : identifier | constant | constant identifier
I honestly don't know where to begin with this and any advice at all would be appreciated.
Regards.
Here is an idea:
1- Create a 0-1 integer variable c_i for each element. The idea is c_i is zero if element is in the first set, and 1 if it is in the second set. You can accomplish that by saying that 0 <= c_i and c_i <= 1.
2- The sum of the elements in the first set can be written as 1*(1 - c_1) + 3*(1 - c_2) + ... +
3- The sum of the elements in the second set can be written as 1*c1 + 3*c2 + ...
While SMT-Lib2 is quite expressive, it's not the easiest language to program in. Unless you have a hard requirement that you have to code directly in SMTLib2, I'd recommend looking into other languages that have higher-level bindings to SMT solvers. For instance, both Haskell and Scala have libraries that allow you to script SMT solvers at a much higher level. Here's how to solve your problem using the Haskell, for instance: https://gist.github.com/1701881.
The idea is that these libraries allow you to code at a much higher level, and then perform the necessary translation and querying of the SMT solver for you behind the scenes. (If you really need to get your hands onto the SMTLib encoding of your problem, you can use these libraries as well, as they typically come with the necessary API to dump the SMTLib they generate before querying the solver.)
While these libraries may not offer everything that Z3 gives you access to via SMTLib, they are much easier to use for most practical problems of interest.

Resources