小编Tob*_*oth的帖子

F#BinarySearch返回位置

我正在尝试在F#中实现一个简单的二进制搜索,作为学习函数式编程的一种方式.我已经在C#中以强制方式实现了它,这是我的主要语言,但我认为通过在F#中以递归的方式实现它来学习函数概念是一个很好的挑战.我已经足够远,它正确地找到了值,我的问题是我希望函数返回-1,如果值不在数组中,否则值的索引,但我无法想出跟踪指数的好方法.这是我的代码:

let rec chop i (nums:array<int>) =
match nums with
| [||] -> -1
| [|x|] -> if x = i then x else -1
| _ -> 
    let mid = nums.Length / 2 in
    if nums.[mid] < i then (chop i nums.[mid..])
    elif nums.[mid] > i then (chop i nums.[..mid])
    else mid

[<EntryPoint>]
let main argv = 
    printfn "%d" (chop 20 (Array.init 100 (fun index -> index * 2)))
    System.Console.ReadKey() |> ignore
    0 // return an integer exit code …
Run Code Online (Sandbox Code Playgroud)

f# functional-programming binary-search

2
推荐指数
2
解决办法
334
查看次数

标签 统计

binary-search ×1

f# ×1

functional-programming ×1