1

I am new to programming in functional languages. I am attempting to implement the F# tryFindIndex function.

let rec tryFindIndex func list =
    match list with
    | [] -> None
    | hd::tl -> if func hd then Some(0)
                else (tryFindIndex func tl) + 1

The issue is with the last line, since adding 1 causes the return type to be 'int' instead of 'int option'. I need to track the index recursively.

4

1 回答 1

4

将索引作为附加参数传递。如果你不这样做,那么你的函数也不是尾递归的。还将您的递归实现为单独的循环以隐藏索引参数。

let tryFindIndex func list =
    let rec loop func list index =
        match list with
        | [] -> None
        | hd::tl -> if func hd then Some(index)
                    else loop func tl (index+1)
    loop func list 0

正如 John 在评论中指出的那样,其核心库实现如下所示:

    let tryFindIndex f list = 
        let rec loop n = function[] -> None | h::t -> if f h then Some n else loop (n+1) t
        loop 0 list
于 2013-07-25T22:53:52.527 回答