Search code examples
.netf#maxminimumunchecked

Maximum / minimum value of type in F#


Unchecked.defaultof<'T> generates the default value for any type. Is there such a generic function to generate the maximum / minimum value for any type where the type having a maximum / minimum value makes sense?

EDIT

To answer John Palmer's question of where I think it would be useful: I want to create a "mutable" version of the below function:

let InternalArrDiffMax (s : 'T []) (diff : 'T -> 'T -> 'C) =
    s
    |> Array.mapi (fun i e -> 
        [| for j in i + 1 .. s.Length - 1 -> diff e s.[j] |]
        |> Array.maxBy (fun n -> n))
    |> Array.maxBy (fun e -> e)

Since I can't declare a mutable variable without assigning value to it, I don't think there is other way to do it than:

let InternalArrDiffMax (s : 'T []) (diffFun : 'T -> 'T -> 'C) =
    let mutable max : 'C = // Generic max of 'C if it makes sense

    for i in 0 .. s.Length - 1 do
        for j in i + 1 .. s.Length - 1 do
            let diff = diffFun s.[i] s.[j]
            if (i = 0 && j = 1) || max < diff then
                max <- diff

    max

Which is why I think I need a generic max.


Solution

  • If you must proceed on this route, there's always Reflection. However, I would advise against use of MaxValue as an out-of-band or special value.

    let inline tryGetMaxValue< ^a> () =
        match typeof< ^a>.GetField("MaxValue") with
        | null -> None
        | fieldInfo -> fieldInfo.GetValue() |> unbox< ^a> |> Some
    
    let maxvi = tryGetMaxValue<int>()            // val maxvi : int option = Some 2147483647
    let maxvf : float option = tryGetMaxValue()  // val maxvf : float option = Some 1.797693135e+308
    let maxvs : string option = tryGetMaxValue() // val maxvs : string option = None