【问题标题】:f# idiomatic type resolution solution for resolving to the wrong typef# 惯用的类型解析解决方案,用于解析到错误的类型
【发布时间】:2014-06-27 10:47:34
【问题描述】:

我刚刚开始使用 F#,但我有一些类似于以下的代码:

let square x = x*x

let result = square 5.1

let result' = square 12

很遗憾,这会导致以下错误:This expression was expected to have type float but here has type int

对于这个问题是否有一个惯用的 F# 解决方案,或者我的想法被我的 C# 经验所污染?

【问题讨论】:

    标签: f# inline type-resolution


    【解决方案1】:

    就这样写吧:

    let inline square x = x * x
    

    否则,在你第一次使用square 函数后,它的类型被推断为float -> float。因此,鉴于 F# 不执行从 intfloat 的自动转换,您会收到错误消息。

    所以,如果你不想使用inline,最简单的解决办法就是写

     let result' = square (float 12)
    

    它简单但可读。

    更多高级解决方案请查看:Does F# have generic arithmetic support?

    但这些解决方案(恕我直言)难以理解。

    【讨论】:

      【解决方案2】:
      let inline square x = x * x
      
      let result = square 5.1
      
      let result' = square 12
      
      printfn "%f" result
      printfn "%d" result'
      

      Tomas Petricek 有一篇关于这个主题的完整文章: http://tomasp.net/blog/fsharp-generic-numeric.aspx/

      【讨论】:

        猜你喜欢
        • 2019-08-18
        • 1970-01-01
        • 2018-05-11
        • 1970-01-01
        • 2020-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多