F#静态成员类型约束 [英] F# Static Member Type Constraints

查看:105
本文介绍了F#静态成员类型约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图定义一个函数,factorize,它使用结构类型约束(需要静态成员零,一,+和/)类似于Seq.sum,以便它可以与int,long,bigint,等等。我似乎不能得到正确的语法,并且找不到很多关于这个主题的资源。

 让inline factorize(n:^ NUM)= 
^ NUM: (static member get_Zero:unit->(^ NUM))
^ NUM:(static member get_One:unit->(^ NUM))
let rec factorize(n:^ NUM) :^ NUM)(flist:^ NUM list)=
如果n = ^ NUM.One then flist
elif n%j = ^ NUM.Zero then factorize(n / j)(^ NUM.One + ^ NUM.One)(j :: flist)
else factorize n(j + ^ NUM.One)(flist)
factorize n(^ NUM.One + ^ NUM.One)[]


解决方案

这里是我写的:

 模块NumericLiteralG = begin 
let inline FromZero()= LanguagePrimitives.GenericZero
let inline FromOne()= LanguagePrimitives.GenericOne
end

let inline factorize n =
let rec factorize nj flist =
if n = 1G then flist
elif n%j = 0G then factor (n / j)j(j :: flist)
else factorize n(j + 1G)(flist)
factorize n(1G + 1G)[]

这里推断的factorize类型太笼统了,但是函数会按照你的期望工作。如果您希望通过向某些通用表达式添加显式类型,可以强制使用更加完整的签名和约束集:

  let inline factorize(n:^ a):^ a list = 
let(one:^ a)= 1G
let(zero:^ a)= 0G
let rec factorize n ^ a)flist =
if n = one then flist
elif n%j = zero then factorize(n / j)j(j :: flist)
else factorn )(flist)
因式分解n(一+一)[]


I'm trying to define a function, factorize, which uses structural type constraints (requires static members Zero, One, +, and /) similar to Seq.sum so that it can be used with int, long, bigint, etc. I can't seem to get the syntax right, and can't find a lot of resources on the subject. This is what I have, please help.

let inline factorize (n:^NUM) =
    ^NUM : (static member get_Zero: unit->(^NUM))
    ^NUM : (static member get_One: unit->(^NUM))
    let rec factorize (n:^NUM) (j:^NUM) (flist: ^NUM list) = 
        if n = ^NUM.One then flist
        elif n % j = ^NUM.Zero then factorize (n/j) (^NUM.One + ^NUM.One) (j::flist)
        else factorize n (j + ^NUM.One) (flist)
    factorize n (^NUM.One + ^NUM.One) []

解决方案

Here's how I'd write it:

module NumericLiteralG = begin
  let inline FromZero() = LanguagePrimitives.GenericZero
  let inline FromOne() = LanguagePrimitives.GenericOne
end

let inline factorize n = 
  let rec factorize n j flist =  
    if n = 1G then flist 
    elif n % j = 0G then factorize (n/j) j (j::flist) 
    else factorize n (j + 1G) (flist) 
  factorize n (1G + 1G) [] 

The type inferred for factorize here is way too general, but the function will work as you'd expect. You can force a more sane signature and set of constraints if you want by adding explicit types to some of the generic expressions:

let inline factorize (n:^a) : ^a list = 
  let (one : ^a) = 1G
  let (zero : ^a) = 0G
  let rec factorize n (j:^a) flist =  
    if n = one then flist 
    elif n % j = zero then factorize (n/j) j (j::flist) 
    else factorize n (j + one) (flist) 
  factorize n (one + one) []

这篇关于F#静态成员类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆