如何在F#中的列表列表中添加元素

时间:2015-10-01 11:56:07

标签: list f#

我有一个这样的列表int int:

let x = [[2; 3; 4]; [4; 5]; [2; 3]]

和一个int例如1.我想在第一个列表中添加这个int并返回如下结果:

[[1; 2; 3; 4]; [4; 5]; [2; 3]]

最方便的方法是什么?

2 个答案:

答案 0 :(得分:2)

let x = [[2; 3; 4]; [4; 5]; [2; 3]]
let addedOne = x |> List.mapi (fun i t -> if i = 0 then 1::t else t)

这会给你:

val x : int list list = [[2; 3; 4]; [4; 5]; [2; 3]]
val addedOne : int list list = [[1; 2; 3; 4]; [4; 5]; [2; 3]]

更通用的功能:

let addToIndex index x l =
  l |> List.mapi (fun i t -> if i = index then x::t else t)

根据Johns解决方案,使用Head的版本:

let addToHead x =
  function
  |[] -> [[x]]
  |h::t -> (x::h)::t 

答案 1 :(得分:2)

一种简单的方法

x |> function |h::t -> (1::h)::t

我们将匹配模式设为第一个子列表h,然后加入它并提供结果。