我最近开始学习如何用F#编程,我的作业给了我一些严重的麻烦.
我必须创建一个函数,它接受两个参数,一个整数和一个五元素的整数元组,如果元组的任何三个元素的总和大于第一个参数,则返回true,否则返回false.
我开始用这种方式设计我的代码
{
let t3 = (1, 2, 3, 4, 5)
let intVal = 1
let check intVal t3 =
for t3
if (*sum of any three elements*) > intVal then true
else false
}
Run Code Online (Sandbox Code Playgroud)
但此时我被困住了,不知道该怎么办.
简单的方法定义 - 对元组的元素进行排序,并与最后三个元素(升序排序)进行比较:
let inline isAnyThreeGreaterThan2 limit (x1, x2, x3, x4, x5) =
[x1;x2;x3;x4;x5] |> List.sort |> Seq.skip 2 |> Seq.sum > limit
Run Code Online (Sandbox Code Playgroud)
例:
isAnyThreeGreaterThan2 15 (1, 2, 5, 5, 5) |> printfn "%A"
isAnyThreeGreaterThan2 14 (1, 2, 5, 5, 5) |> printfn "%A"
isAnyThreeGreaterThan2 15 (1, 2, 5, 5, 6) |> printfn "%A"
isAnyThreeGreaterThan2 15 (1, 2, 3, 4, 5) |> printfn "%A"
isAnyThreeGreaterThan2 12 (1, 2, 3, 4, 5) |> printfn "%A"
isAnyThreeGreaterThan2 11 (1, 2, 3, 4, 5) |> printfn "%A"
Run Code Online (Sandbox Code Playgroud)
打印:
false
true
true
false
false
true
Run Code Online (Sandbox Code Playgroud)
链接:
https://dotnetfiddle.net/7XR1ZA