Explicitly specifying parameter types in F#

非 Y 不嫁゛ 提交于 2020-01-24 11:11:06

问题


I'm writing an F# function that factorises a number into prime factors.

let factors primes i =
    let mutable j = i
    for p in primes do 
        while (j>1) && (j%p=0) do 
            j <- j/p
            printfn "prime: %i" p

It works for int values of i, but not int64 values. The parameter primes is a set of int values.

I understand why this is the case - type inference is assuming that the function only takes int parameters - but I want to explicitly specify the parameter type as int64.

Is it possible to write this function so that it will work for both int and int64?


回答1:


If you want to work only on int64 values, just replace 1 and 0 with 1L and 0L respectively. jpalmer's answer covers the generic case.




回答2:


You will have to do something like

let inline factors (primes :^a list) (i:^a) =
    let zero:^a = LanguagePrimitives.GenericZero
    let one:^a = LanguagePrimitives.GenericOne
    let mutable j = i
    for p in primes do 
        while (j>one) && (j%p=zero) do 
            j <- j/p
            printfn "prime: %i" p

I don't have the compiler, so my syntax may be slightly off



来源:https://stackoverflow.com/questions/7577437/explicitly-specifying-parameter-types-in-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!