簡體   English   中英

輸出列表中的前 n 個元素

[英]Outputting first n elements in the list

你如何編寫一個 f# 遞歸 function 接受一個正的 integer n 和一個列表 xs 作為輸入,並返回一個僅包含 xs 中的前 n 個元素的列表。

讓 rec 某事 n xs =.. 某事 3 [1..10] = [1;2;3]

簡短的回答是:不要,只需使用Seq.take

一個簡單的版本是這樣的:

let rec take n list = 
  match n with
  | 0 -> []
  | _ -> List.head list :: take (n - 1) (List.tail list)

尾遞歸可能如下所示:

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 []

請注意,這些都不能處理輸入列表短於請求的項目數的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM