Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly specifying parameter types in F#

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?

like image 385
Kirk Broadhurst Avatar asked Dec 28 '25 06:12

Kirk Broadhurst


2 Answers

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

like image 106
John Palmer Avatar answered Dec 30 '25 23:12

John Palmer


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.

like image 28
kvb Avatar answered Dec 31 '25 00:12

kvb