Are there tricks for doing implicit conversions in F#?

前端 未结 2 1346
挽巷
挽巷 2020-12-11 19:09

Consider this F# code to sum the numbers below i that are multiples of 3 and 5:

let isMultipleOfThreeOrFive n = 
    (n % 3 = 0) || (n % 5 = 0)
         


        
相关标签:
2条回答
  • 2020-12-11 20:00

    You did the best thing.

    (There is not an easier way to "get around" it than by adding the six characters you added. Even without implicit conversions, the F# is shorter than the C#, and the delta change-from-int-to-BigInteger is also smaller in F# than C#. So don't be sad about the loss of implicit conversion - be happy about all the other succinctness wins. :) )

    0 讨论(0)
  • 2020-12-11 20:06

    This doesn't exactly answer your question, but note that it's also possible to make sequenceOfMultiples generic by defining your own numeric literal:

    module NumericLiteralG =
      let inline FromZero() = LanguagePrimitives.GenericZero
      let inline FromOne() = LanguagePrimitives.GenericOne
      let inline FromInt32 (i:int) =
        let zero : ^a = FromZero()
        let one : ^a = FromOne()
        let rec compute : int -> ^a = function
        | 0 -> zero
        | n -> 
            let half = compute (n/2)
            let whole = half + half
            if (n%2 = 0) then whole
            else whole + one
        compute i
    
    let inline isMultipleOfThreeOrFive n = 
        (n % 3G = 0G) || (n % 5G = 0G)
    
    let inline sequenceOfMultiples i =
        seq {1G .. i - 1G} |> Seq.filter isMultipleOfThreeOrFive
    
    let bigintSeq = sequenceOfMultiples 100I
    let intSeq = sequenceOfMultiples 100
    
    // doesn't compile
    let stringSeq = sequenceOfMultiples "100"
    
    0 讨论(0)
提交回复
热议问题