To add to Daniel's answer, the F# type system doesn't provide a way to define a subrange type -- that is, a type representing some subset of the values representable by an existing type (e.g., System.Double).

On the plus side, there are a couple of workarounds you can use to help enforce the constraint (+/- 1.0) in the type system. IMO, the easiest way would be to define an F# measure type and use that to "track" which values in your code represent interest rates (and therefore, need to be restricted to a certain range of values) and those which aren't. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/// Interest rate. Should be restricted to values in the range [-1.0, 1.0].
[<Measure>] type InterestRate

/// Type abbreviation for interest rate values.
type IR = float<InterestRate>

/// Functions for working with interest rates.
[<RequireQualifiedAccess; CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module InterestRate =
    /// Gets the interest-rate value as a System.Double.
    let inline toFloat (value : IR) = float value
    /// Creates an interest-rate value from a System.Double.
    let inline ofFloat value =
        if value < -1.0 || value > 1.0 then
            raise <| System.ArgumentOutOfRangeException ("value")
        else
            LanguagePrimitives.FloatWithMeasure<InterestRate> value
By on 1/13/2012 12:22 PM ()

Thanks Daniel and Jack, Both responses are what I needed but Jack's expanded version to utilize Measures is exactly what I was hoping to achieve.

By on 1/16/2012 2:41 AM ()

Something like this:

1
2
3
4
5
type IR(value) =
  do
    if value < 1.0 || value > 1.0 then
      invalidArg "value" "Limited to +/- 1.0"
  member x.Value = value

Usage:

1
2
3
let printIR (x:IR) = printfn "Interest rate is: %f" x.Value

printIR (IR 1.0)
By on 1/13/2012 11:25 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper