How to update values โโin a list of type <T> in F #?
I'm currently learning F # and at the same time struggling a little to understand how clearly discriminatory unions and notations work.
I would like to know how can I update some values โโfrom a list like <'T>?
My code
type Position =
| Location of (int * int)
type Ship =
{
Position : Position;
Projectiles : List<Position>;
}
I create a ship instance:
let aShip =
{
Position: Location(1,5);
Projectiles: [Location(1,1);Location(2,5)]
}
Now I tried to loop over the projectiles, but I get this:
for elem in aShip.Projectiles do
printfn "%A" elem
// prints out
Location(1,1)
Location(2,5)
But I like getting the values โโ(1.1) and (2.5) back, how could I achieve this?
source to share
Discriminatory unions can be destructured by providing a template with some places in it occupied by identifiers. The compiler will then generate code that tries to match this pattern to the data and binds the data points to the appropriate identifiers. For example:
let loc = Location (1,2)
let (Location (x,y)) = loc
On the second line, the compiler will generate code, "make sure this is Location
, then bind the first int to name x
, and the second int to name y
"
Alternatively, you can use the more verbose syntax match
:
let x = match loc with Location(x,y) -> x
This is too much in your particular case, but for discriminated joins with multiple cases, this match
is the only way to deal with all of them, for example:
type Position =
| Location of int*int
| Unknown
let xOrZero =
match loc with
| Location(x,y) -> x
| Unknown -> 0
The examples above show how patterns can appear in let
and within expressions match
, but that's not all. In F #, almost everything you think of as a "variable declaration" is actually a template. It's just that most time patterns are trivial, as in let x = 5
, but they don't have to be - for example.let x,y = 5,6
It follows from what has been said that elem
in is for elem in ...
also a pattern. This means that you can destroy an element in place:
for Location(x,y) in aShip.Projectiles do
printfn "%d,%d" x y
Or, if you want to highlight a couple of the whole, rather than x
and y
individually, it is also possible:
for Location xy in aShip.Projectiles do
printfn "%A" xy
source to share