Mapping/translating an object to another in F#

I'm a beginner to F# and playing around with it, until I faced this problem. I searched for it but couldn't find anything. I want to mutate an object into another. I have Geolocation object With lots of properties, two of them the Latitude and Longitude. I want to create a new dynamic object but using a pipe or a select operator, with only that subset of properties

let customLocation = OtherPlace.Geolocation ....

how can I do this?


The best way to solve this sort of problem is to create a discriminated union with a single case. You could use a straight type alias, but you would lose a small amount of type safety. To define the type use:

type Loc = |LL of float * float

and then you can create instances with something like:

Something |> fun t -> LL(t.Latitude,t.Longitude)

or the simpler version:


let's say you have an array of OtherPlace.Geolocation

geoLocations :  OtherPlace.Geolocation array

you can then, depending on your need :

  • use a tuple (which is just a special case of a record)


 //of type (double * double) array
let g = geoLocations |> (fun x -> x.Latitude, x.Longitude)  
  • create a record type (nb : a tuple is just a record with positional names)


type Position = {Latitude : double; Longitude : double}

//of type Position array
let g = geoLocations |> (fun x -> x.Latitude, x.Longitude) 

For small local need, a tuple is better suited but can become unwieldy.

Records allow you to better structure the program

Union case should be used to differentiate between different things, that still represent some common concept. For instance you could have the position to be expressed in different system

type GeoPosition = | LaTLong of double * double
                   | WGS84 of double * double
                   | ...

//of type GeoPosition array
let g = geoLocations |> (fun x -> LatLong (x.Latitude, x.Longitude))  

PS : if you use F# 3.1 you have one additional sugar for naming union type fields as shown here

Need Your Help

using php in css to target a unique object class

php html css

i have a page that automatically adds a number to a objects class name like this

Simple UI testing a button click with karma and qUnit

qunit karma-runner

I have figured out how to test my code with the karma test runner, but I cannot figure out how to test the UI features on a web page.