fsharp 从列表中获取第 n 个元素

fsharp get nth element from a list

这是一个非常简单的问题,但我只是不熟悉模式匹配和 f# 语法。

我正在尝试编写一个函数,它接受一个 int 和一个 a' 列表,以及 return a' 类型的第 n 个元素。我在想这样的事情:

let rec getn n xs=
  match n with
  0 -> {split xs into x::xs and then return x}
  _ -> {split xs into x::xs and call getn with n-1, xs}

有人可以帮我解决语法问题吗? 谢谢

let rec getn n xs =
    match n, xs with
      | 0, (x::_)   -> x
      | _, (_::xs') -> getn (n - 1) xs'
      | _, []       -> invalidArg "n" "n is too large"

我认为 ifmatch 更清楚:

let rec getn n xs =
    if List.isEmpty xs then invalidArg "n" "n is too large"
    let x::xs' = xs in if n = 0 then x else getn (n - 1) xs'

列表支持索引,[i]

let alist = [1..9] 
let n = 5

alist.[n-1] |> Console.Write