Unchecked.defaultof<'T>为任何类型生成默认值。 是否有这样一种通用函数来为任何类型生成最大值/最小值,其中最大/最小值的类型是有意义的?
编辑
回答John Palmer关于我认为它会有用的问题:我想创建下面的函数的“可变”版本:
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)由于我不能声明一个可变变量而没有给它赋值,我不认为还有其他方法可以做到这一点:
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这就是为什么我认为我需要一个通用的最大。
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 maxWhich is why I think I need a generic max.
最满意答案
如果你必须继续这条路线,那么总是有反思。 不过,我建议不要使用MaxValue作为带外或特殊价值。
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 = NoneIf 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发布者:admin,转转请注明出处:http://www.yc00.com/web/1692267761a580038.html
评论列表(0条)