【问题标题】:Function working for all numerical data types适用于所有数值数据类型的函数
【发布时间】:2014-05-30 17:05:10
【问题描述】:

我写了一个简单的函数来反转给定的数字:

let reverseNumber x =
    let rec innerFunc acc elem =
        if elem = 0
            then acc
            else 
                let rem = elem % 10
                innerFunc (10 * acc + rem) (elem / 10)

    innerFunc 0 x

问题是它只适用于整数。例如int64 我需要创建另一个版本,分别使用0L10L 而不是010

我听说可以使用 inline 关键字和 LanguagePrimitives 编写更通用的函数,但后者既不包含提醒操作也不包含 'GenericTen'(尽管这可能通过 'GenericOne + GenericOne + ... 获得) .

你能帮忙吗?

【问题讨论】:

标签: f# inline generic-programming


【解决方案1】:

忽略@kvb 链接答案的完整性,这是使其通用的最少工作:

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

let inline reverseNumber (x:^a) =
    let ten:^a = 1G + 1G + 1G + 1G + 1G + 1G + 1G + 1G + 1G + 1G
    let rec innerFunc (acc:^a) (elem:^a) =
        if elem = 0G then acc
        else
            let (rem:^a) = elem % ten
            innerFunc (ten * acc + rem) (elem / ten)
    innerFunc 0G x

类型注释不是绝对必要的,仅用于减少 IntelliSense 中列出的类型约束;没有它们,代码也能正常工作。

【讨论】:

    猜你喜欢
    • 2021-07-17
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多