我正在做一项家庭作业,需要用F#编写一个函数,该函数接受表示立方体的维度(长度、宽度和高度)的浮点元组列表,并返回具有最大体积的立方体的体积。
每个元组由三个都大于零的浮点值组成。立方体的体积使用(长x宽x高)计算。如果列表为空,则返回0.0。
当我们不允许使用不可变变量List.map或max时,我真的不知道如何在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#中做到这一点?
发布于 2020-03-21 01:26:09
//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 |> volhttps://stackoverflow.com/questions/60746879
复制相似问题