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)]]
它不工作,但我更關心的辦法。這是對的嗎?
你想達到什麼目的? –
對不起@FyodorSoikin,我忘了指定問題。現在應該沒問題。 – Worice
看看這裏:https://fsharpforfunandprofit.com/posts/elevated-world/ –