【问题标题】:F#: writing a function for maxCubeVolume?F#:为 maxCubeVolume 编写函数?
【发布时间】:2020-03-18 20:13:34
【问题描述】:

我正在做一个家庭作业,需要在 F# 中编写一个函数,该函数接受代表立方体尺寸(长度、宽度和高度)的浮点元组列表,并返回具有最大的体积。

每个元组由三个都大于零的浮点值组成。立方体的体积使用(长 x 宽 x 高)计算。如果列表为空,则返回 0.0。

当我们不允许使用不可变变量List.mapmax 时,我真的不知道如何在 F# 中实现这一点。

到目前为止我所做的是:

let listTup = [(2.1, 3.4, 1.8); (4.7, 2.8, 3.2); (0.9, 6.1, 1.0);]
let cubeVolume (x, y, z) : float = x * y * z
let maxCubeVolume tupleList = ???

maxCubeVolume listTup 应该返回 42.112

如何在 F# 中执行此操作?

【问题讨论】:

  • 从一个递归函数开始,该函数携带最大体积和元组。以 (0,0,0) 0 的初始值调用它。

标签: f# f#-interactive


【解决方案1】:
//using the "not allowed" List.map and List.max
[(2.1, 3.4, 1.8); (4.7, 2.8, 3.2); (0.9, 6.1, 1.0)]
|> List.map (fun (l,w,h) -> l*w*h) |> List.max

//using List.fold: the if branch could be a max vol acc, but you said max wasn't allowed
(0.,[(2.1, 3.4, 1.8); (4.7, 2.8, 3.2); (0.9, 6.1, 1.0)])
||> List.fold (fun acc (l,w,h) -> l*w*h |> fun vol -> if vol > acc then vol else acc)

//using List.maxBy
let vol (l,w,h) = l*w*h
[(2.1, 3.4, 1.8); (4.7, 2.8, 3.2); (0.9, 6.1, 1.0)]
|> List.maxBy vol |> vol

//using List.sortBy
let vol (l,w,h) = l*w*h
[(2.1, 3.4, 1.8); (4.7, 2.8, 3.2); (0.9, 6.1, 1.0)]
|> List.sortBy (vol >> (*)-1.) |> List.head |> vol

【讨论】:

    猜你喜欢
    • 2018-10-03
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多