在F#中使用选项类型实现tryFindIndex

时间:2013-07-25 22:40:43

标签: f#

我是函数式语言编程的新手。我正在尝试实现F#tryFindIndex函数。

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

问题在于最后一行,因为添加1会导致返回类型为'int'而不是'int option'。我需要递归地跟踪索引。

1 个答案:

答案 0 :(得分:3)

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

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

正如约翰在评论中指出的那样,核心库的实现如下:

    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
相关问题