我的 F# 函数中没有获取基本案例
Base case not getting picked up in my F# function
这个函数应该只是 return 列表的索引。那部分有效。但是,当元素不在列表中时,它必须 return -1.
出于某种原因,它没有 return -1。
let rec search f list =
match list with
| head::tail ->
if f head then 0
else 1 + search f tail
| [] -> -1
printfn "%A" (search (fun x -> x = 5) [ 5; 4; 3; 2 ])
//>> return index 0 for #5
printfn "%A" (search (fun x -> x = 6) [ 5; 4; 3; 2 ])
//>> should return -1 but it returns 3 which is the len of the list not -1
编辑:不能使用嵌套函数。
您可以使用例如
let search f list =
let rec where at list =
match list with
| [] -> -1
| head::tail ->
if f head then at
else where (at + 1) tail
where 0 list
具有 tail-recursive 的优势。关于您的评论:
let rec search f list =
match list with
| [] -> -1
| head::tail ->
if f head then 0 else
match search f tail with
| -1 -> -1
| i -> i + 1
这个函数应该只是 return 列表的索引。那部分有效。但是,当元素不在列表中时,它必须 return -1.
出于某种原因,它没有 return -1。
let rec search f list =
match list with
| head::tail ->
if f head then 0
else 1 + search f tail
| [] -> -1
printfn "%A" (search (fun x -> x = 5) [ 5; 4; 3; 2 ])
//>> return index 0 for #5
printfn "%A" (search (fun x -> x = 6) [ 5; 4; 3; 2 ])
//>> should return -1 but it returns 3 which is the len of the list not -1
编辑:不能使用嵌套函数。
您可以使用例如
let search f list =
let rec where at list =
match list with
| [] -> -1
| head::tail ->
if f head then at
else where (at + 1) tail
where 0 list
具有 tail-recursive 的优势。关于您的评论:
let rec search f list =
match list with
| [] -> -1
| head::tail ->
if f head then 0 else
match search f tail with
| -1 -> -1
| i -> i + 1