F# 检查列表是否为空

F# 检查列表是否为空,f#,functional-programming,F#,Functional Programming,作为一名F#新手,我尝试实现一个简单的函数,该函数将索引和列表作为参数,然后返回给定索引的列表值 let rec getElementAtIndex (index : int) (list : 'a list) = match index, list with | _ ,[] -> failwith "index is greater than number of elements in list.." | _, _ when index < 0 -> f

作为一名F#新手,我尝试实现一个简单的函数,该函数将索引和列表作为参数,然后返回给定索引的列表值

let rec getElementAtIndex (index : int) (list : 'a list) = 
  match index, list with
    | _ ,[] -> failwith "index is greater than number of elements in list.."
    | _, _ when index < 0 -> failwith "index is less than 0." 
    | 0, (first::_) -> first
    | _, (_::rest') -> getElementAtIndex (index - 1) rest'
如何避免这种情况,并在不使用.net库方法的情况下分别检查列表是否为空以及给定的索引是否大于列表大小

任何帮助都将不胜感激

检查全局预条件的模式是嵌套函数,即首先检查预条件,然后开始使用实际工作递归。这样,递归函数变得更简单,并且在保护或
长度
时不需要

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)
更新

您可以使用
匹配列表与[]->匹配列表与“…”|u->()
如果列表与[]],则与“…”匹配,后者仅适用于支持相等的元素列表。

检查全局先决条件的模式是嵌套函数,也就是说,首先检查前提条件,然后开始实际工作的递归。这样,递归函数变得更简单,并且在
保护或
长度
时不需要

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)
更新


您可以使用
将列表与[]->匹配,而不是
如果List.isEmpty List那么failwith“List is empty”
使用
将列表与[]->匹配,或者
如果List=[]那么failwith“…”
后者仅适用于支持相等的元素列表。

在这两种情况下,错误消息看起来都是正确的。问题是什么?我认为检查列表是否为空和检查给定索引是否超出范围是两码事。如果您对遍历列表以确定其长度的效率低下感到满意,您可以使用
List.length
@molbdnilo有没有办法不使用库函数来完成此操作?自己编写
length
非常简单。在这两种情况下,错误消息看起来都是正确的。问题是什么?我认为检查列表是否为空和检查给定索引是否超出范围是两码事。如果您对遍历列表以确定其长度的效率低下感到满意,您可以使用
List.length
@molbdnilo有没有不使用库函数的方法?自己编写
length
很简单。我已经在解决方案中这样做了。我希望能够在不使用.net库中的帮助函数的情况下检查给定的列表参数是否为空列表。@tartart,此解决方案能够区分您所要求的错误情况。这里根本没有使用.NET函数。如果
isEmpty
属性是反对的原因,那么这实际上是一个与实际空列表的简单匹配,请参见我在解决方案中已经这样做了。我希望能够在不使用.net库中的帮助函数的情况下检查给定的列表参数是否为空列表。@tartart,此解决方案能够区分您所要求的错误情况。这里根本没有使用.NET函数。如果
isEmpty
属性是反对的原因,那么这实际上是与实际空列表的简单匹配,请参阅
  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