我想在F#中找到没有.NET的数组中的最大值,最小值和平均值.我使用了这段代码,但它没有用:
let mutable max = 0
let arrX = [|9; 11; 3; 4; 5; 6; 7; 8|]
for i in 0 .. arrX.Length - 2 do
if (arrX.[i]) < (arrX.[i+1]) then
max <- arrX.[i]
printfn "%i" max
Run Code Online (Sandbox Code Playgroud)
虽然已经发布的答案是,为什么你贴的代码不起作用完全有效的,我认为使用一个循环和一个可变变量是不是很... 功能.所以我想我会发布更多的F# - 惯用的解决方法.
你声明你"不能使用.NET".我猜你的意思是你不能使用任何内置函数或.NET库.当然,这也意味着您可以使用F#原语自己实现它们.
功能世界中的一个常见功能是fold,它只是将一个函数应用于序列的所有元素,同时保持该函数在累加器中的返回.内置版本是Seq.fold,但由于我们不能使用它,我们将自己定义一个:
let rec fold accFn arr acc =
match arr with
| [||] -> acc
| _ -> fold accFn arr.[1..] (accFn arr.[0] acc)
Run Code Online (Sandbox Code Playgroud)
这是一个递归函数,它将accFn函数应用于每个元素,然后使用数组的其余部分调用自身.当它传递一个空数组时,递归终止.
当我们有了这个时,让我们定义一些简单的函数来传递fold:
let min x y =
if x < y then x
else y
let max x y =
if x > y then x
else y
let sum x y =
x + y
Run Code Online (Sandbox Code Playgroud)
一旦我们有了这个,解决所述问题很简单:
let arrX= [|9; 11; 3; 4; 5; 6; 7; 8|]
let head = arrX.[0]
let avg = (fold sum arrX 0) / arrX.Length
let minValue = fold min arrX head
let maxValue = fold max arrX head
Run Code Online (Sandbox Code Playgroud)
我修复了你的代码 max
let mutable max = 0
let arrX= [|9; 11; 3; 4; 5; 6; 7; 8|]
for i in 0 .. arrX.Length - 1 do
if max < (arrX.[i]) then
max <- arrX.[i]
printfn "%i" max
Run Code Online (Sandbox Code Playgroud)
要查找最大值、最小值和平均值,请使用您的方法:
let mutable max = System.Int32.MinValue
let mutable min = System.Int32.MaxValue
let mutable sum = 0
let arrX= [|9; 11; 3; 4; 5; 6; 7; 8|]
for i in 0 .. arrX.Length - 1 do
if max < (arrX.[i]) then
max <- arrX.[i]
printfn "max %i" max
if min > (arrX.[i]) then
min <- arrX.[i]
printfn "min %i" min
sum <- sum + arrX.[i]
printfn "-> max is %i" max
printfn "-> min is %i" min
printfn "-> avg is %f" (float sum / float arrX.Length)
Run Code Online (Sandbox Code Playgroud)
但请注意,您可以这样做:
let max = Seq.max arrX
let min = Seq.min arrX
let avg = Seq.averageBy float arrX
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5290 次 |
| 最近记录: |