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

时间:2015-01-26 00:20:26

标签: f# pattern-matching

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

我正在尝试编写一个带有int和a'列表的函数,并返回类型为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}

有人可以帮我解决这个问题吗? 感谢

1 个答案:

答案 0 :(得分:3)

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

我认为if会比match更明确:

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'