【问题标题】:List of integers to Float in F#在 F# 中浮点数的整数列表
【发布时间】:2020-10-27 18:12:00
【问题描述】:

我刚开始使用 FSharp 并有这个功课,希望任何人都可以帮助我。 我必须编写一个程序,它接受一个整数列表并返回一个浮点数。应按连分数计算。 所以如果 int 列表是 [4; 5个; 6] 浮点数将通过以下方式计算:4 + (1 / (5 + 1/6) )

函数必须是递归的。 我写了以下内容:

let rec fractionDecimal (numberlist : int list) : float =
  match numberList with
    |[] -> 0.0
    | x :: y -> x + 1.0 / fractionDecimal y

它不起作用,因为 (fractionDecimal y) float 与 int 类型不匹配。 您对如何解决问题或如何使我的代码正常工作有任何建议吗? 提前致谢

【问题讨论】:

    标签: design-patterns f# match


    【解决方案1】:

    问题是您试图将1.0 / fractionDecimal tail 的值float 添加到headint

    您可以使用float 函数解决这种情况。

    let rec fractionDecimal (numberList : int list) : float =
        match numberList with
        | [] -> 0.0
        | head :: tail -> float head + 1.0 / fractionDecimal tail
    

    这个 Microsoft 文档很好地描述了这里发生的事情:https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/compiler-messages/fs0001

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 2013-06-29
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 2019-04-26
      • 1970-01-01
      • 2021-03-24
      相关资源
      最近更新 更多