检查的模式
全球的
实际的
工作。通过这种方式,递归函数变得更简单,并且不需要
when
警卫或
length
:
let getElementAtIndex index list =
if index < 0 then failwith "index is less than 0"
if List.isEmpty list then failwith "list is empty"
let rec get = function
| _ , [] -> failwith "index is greater than number of elements in list"
| 0, first::_ -> first
| _, _::rest -> get(index - 1, rest)
get(index, list)
这个
function
let rec get i l =
match i, l with
| _ , [] -> failwith "index is greater than number of elements in list"
| 0, first::_ -> first
| _, _::rest -> get (index - 1) rest
更新
if List.isEmpty list then failwith "list is empty"
你可以用
match list with [] -> failwith "..." | _ -> ()
或
if list = [] then failwith "..."
后者只适用于支持平等的元素列表。