F Sharp (programming language): Difference between revisions

Content deleted Content added
Shr2012 (talk | contribs)
External links: removed non-existent, no longer relevant links
Shr2012 (talk | contribs)
m Units of measure: It can now support signed and unsigned integers. Couple of code examples added.
Line 463:
 
===Units of measure===
The F# type system supports [[Units of measurement|units of measure]] checking for numbers.<ref name="units-msdn">{{cite web |url=http://msdn.microsoft.com/en-us/library/dd233243.aspx |title=Units of Measure (F#) |access-date=2012-11-24}}</ref> The units of measure feature integrates with F# type inference to require minimal type annotations in user code.<ref name="units">{{cite web |url=http://blogs.msdn.com/b/andrewkennedy/archive/2008/08/29/units-of-measure-in-f-part-one-introducing-units.aspx |title=Units of Measure in F#: Part One, Introducing Units |access-date=2012-11-24}}</ref>
 
In F#, you can assign units of measure, such as meters or kilograms, to floating point, unsigned integer<ref name="units extended">{{cite web|url=https://github.com/fsharp/fslang-design/blob/main/FSharp-6.0/FS-1091-Extend-Units-of-Measure.md| title=Extend Units of Measure to Include More Numeric Types }}</ref> and signed integer values. This allows the compiler to check that arithmetic involving these values is dimensionally consistent, helping to prevent common programming mistakes by ensuring that, for instance, lengths aren't mistakenly added to times.
 
The units of measure feature integrates with F# type inference to require minimal type annotations in user code.<ref name="units">{{cite web |url=http://blogs.msdn.com/b/andrewkennedy/archive/2008/08/29/units-of-measure-in-f-part-one-introducing-units.aspx |title=Units of Measure in F#: Part One, Introducing Units |access-date=2012-11-24}}</ref>
 
 
<syntaxhighlight lang="fsharp">
[<Measure>] type m // meter
[<Measure>] type s // second
 
let distance = 100.0<m> // float<m>
let time = 5.0<s> // float<s>
let speed = distance/time // float<m/s>
 
 
[<Measure>] type kg // kilogram
[<Measure>] type N = (kg * m)/(s^2) // Newtons
[<Measure>] type Pa = N/(m^2) // Pascals
 
[<Measure>] type days
let better_age = 3u<days> // unit<days>
 
</syntaxhighlight>
 
Note: The F# static type checker provides this functionality at compile time, but units are erased from the compiled code. Consequently, it is not possible to determine a value's unit at runtime.
 
===Metaprogramming===