【问题标题】:F# question about typing, the type float*float does not match the type 'float'F#关于打字的问题,float*float类型与'float'类型不匹配
【发布时间】:2020-05-20 04:48:03
【问题描述】:

我开始学习 F#,但对类型问题感到困惑。 对于上下文,我正在搜索给定包含半径、高度的元组列表的圆柱体的最大体积

我得到一个“这个表达式应该有'float'类型,但是当我调用recMax hd t1时这里有'float*float'类型

let CylinderVolume ((radius, height) : float*float) =
height * System.Math.PI * radius * radius

let maxCylinderVolume list : float =
    match list with
        | [] -> 0.0
        | hd :: t1 ->
            let rec recMax maxSoFar items = 
                match items with
                | [] -> maxSoFar
                | hd :: t1 ->
                    if (CylinderVolume hd) > maxSoFar then
                        recMax (hd) t1
                    else
                        recMax  maxSoFar t1
            recMax hd t1

【问题讨论】:

  • 你想要最大音量,不应该是recMax (CylinderVolume hd) t1吗?

标签: list f# tuples


【解决方案1】:

您收到此错误是因为当 recMax 需要浮点数时,您使用 hd 调用 recMax,这是一个元组。

let maxCylinderVolume lst =
    let rec recMax maxSoFar items =
        match items with
        | [] -> maxSoFar
        | h :: t -> let volume = cylinderVolume h
                    if maxSoFar < volume 
                    then recMax volume t 
                    else recMax maxSoFar t
    recMax 0.0 lst 

但是你应该看看 List 模块,它提供了更简单地做你想做的事情的功能。

let maxCylinderVolume = List.map cylinderVolume >> List.max

【讨论】:

  • List.maxBy 避免分配新的中间列表。
  • 是的,但是 List.maxBy CylinderVolume 返回一个 float * float 元组,并且 OP 希望返回是一个 float
  • 是的,根据元素的数量,再次计算体积可能仍然有意义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-25
  • 1970-01-01
  • 2019-02-24
相关资源
最近更新 更多