[英]Outputting first n elements in the list
How do you write a f# recursive function that accepts a positive integer n and a list xs as input, and returns a list containing only the first n elements in xs.你如何编写一个 f# 递归 function 接受一个正的 integer n 和一个列表 xs 作为输入,并返回一个仅包含 xs 中的前 n 个元素的列表。
let rec something n xs =.. something 3 [1..10] = [1;2;3]让 rec 某事 n xs =.. 某事 3 [1..10] = [1;2;3]
The short answer is: Don't, just use Seq.take
.简短的回答是:不要,只需使用
Seq.take
。
A simple version would be something like:一个简单的版本是这样的:
let rec take n list =
match n with
| 0 -> []
| _ -> List.head list :: take (n - 1) (List.tail list)
A tail-recursive could look like:尾递归可能如下所示:
let rec take n list =
let rec innertake m innerlist acc =
match m with
| 0 -> List.rev acc
| _ -> innertake (m - 1) (List.tail innerlist) ((List.head innerlist) :: acc)
innertake n list []
Note that neither of these does anything to handle the case that the input list is shorter than the requested number of items.请注意,这些都不能处理输入列表短于请求的项目数的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.