中进行隐式转换的技巧

中进行隐式转换的技巧

本文介绍了是否有在 F# 中进行隐式转换的技巧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个 F# 代码来求和 i 下面是 3 和 5 的倍数的数字:

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)

let sequenceOfMultiples i =
    seq {1 .. i - 1} |> Seq.filter isMultipleOfThreeOrFive

由于 iint,如果 i 很大,你会溢出.这个带有 BigInteger 的版本可以解决这个问题:

Since i is an int, you'll overflow if i is large. This version with BigInteger takes care of that:

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

let sequenceOfMultiples (i : System.Numerics.BigInteger) =
    seq {1I .. i - 1I} |> Seq.filter isMultipleOfThreeOrFive

要将int 版本转换为BigInteger 版本,我必须在数字后添加许多I.这是因为 F# 不进行隐式转换.

To convert the int version to the BigInteger version, I had to add lots of Is after the numbers. This is because F# doesn't do implicit conversions.

有没有简单的方法可以解决这个问题,或者在 6 个地方添加 I 是最好的做法?

Is there an easy way to get around this, or was adding Is in 6 places the best thing to do?

推荐答案

你做得最好.

(没有比添加您添加的六个字符更简单的绕过"方法了.即使没有隐式转换,F# 也比 C# 短,并且 delta 从 int 变为 BigInteger在 F# 中也比 C# 小.所以不要为隐式转换的损失感到难过 - 为所有其他简洁性获胜而感到高兴.:) )

(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. :) )

这篇关于是否有在 F# 中进行隐式转换的技巧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:50