2016-11-21 62 views
4

我构建了一个简单的函数,在给定列表的情况下,返回该列表的第一个n元素。列表清单上的操作

let rec first l n = 
    match l, n with 
    (_, 0) -> l 
    | (x::xs 1) -> [x] 
    | (x::xs n) -> x::(first xs (n-1)) 

但是如果输入是列表列表而不是列表呢?我想建立一个函数,给出一个列表,从返回每个列表中的第一个n元素。 例如:

first [[1; 2]; [5; 6; 7]; []; []; [9; 8; 0]] 1 = 
[1; 5; 9] 

我试图找出一种方法,通过使模式列表的列表:

let rec first l n = 
    match l, n with 
    (_, 0) -> l 
    | ([[x]::[xs]], n) -> [x::[first xs (n-1)]] 

它不工作,但我更关心的办法。这是对的吗?

+1

你想达到什么目的? –

+0

对不起@FyodorSoikin,我忘了指定问题。现在应该没问题。 – Worice

+1

看看这里:https://fsharpforfunandprofit.com/posts/elevated-world/ –

回答

8

可以实现这样的功能

let firsts i = List.map (List.truncate i) 

let firsts' i = List.map (List.take i) 

这取决于你想如何它的行为是否有在列表中的一个元素的数量不足。

> firsts 2 [[1..10]; [11..20]; [21..30]];; 
val it : int list list = [[1; 2]; [11; 12]; [21; 22]] 
+0

感谢马克的回答,它一如既往地简洁明了。 – Worice