【发布时间】:2018-09-18 02:31:24
【问题描述】:
作为一个 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'
我的解决方案工作正常,但是当我给出的索引参数大于列表大小并且当我给出一个空列表作为参数时,在这两种情况下都会进入相同的条件,即
| _ ,[] -> failwith "index is greater than number of elements in list."
在不使用 .net 库方法的情况下,如何避免这种情况并检查列表是否为空并且给定的索引是否大于列表大小?
任何帮助将不胜感激
【问题讨论】:
-
两种情况下的错误信息看起来都是正确的。有什么问题?
-
我认为检查列表是否为空和检查给定索引是否超出范围是不同的事情。
-
如果您对遍历列表以确定其长度的低效率感到满意,您可以使用
List.length。 -
@molbdnilo 有没有办法在没有库函数的情况下做到这一点?
-
自己写
length很简单。