Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
集合的F#子集_F# - Fatal编程技术网

集合的F#子集

集合的F#子集,f#,F#,嗨,我想写一个函数,它接受一个整数列表,并返回该列表所有子集的列表 例如[5;9;7]将不按特定顺序返回[5;9;7];[5;9];[5;7];[9;7];[5];[9];[7]] 我一辈子都不知道该怎么做。我在网上查了一下,我能找到的唯一解决办法是 module Set = /// Returns all subset of a specified set. For example, for input [1;2;3], /// the result will be a set co

嗨,我想写一个函数,它接受一个整数列表,并返回该列表所有子集的列表

例如[5;9;7]将不按特定顺序返回[5;9;7];[5;9];[5;7];[9;7];[5];[9];[7]]

我一辈子都不知道该怎么做。我在网上查了一下,我能找到的唯一解决办法是

module Set = 
  /// Returns all subset of a specified set. For example, for input [1;2;3],
  /// the result will be a set containing sets [1;2;3], [1;2], [1;3], [2;3]
  /// [1], [2], [3] and [].
  let rec subsets s = 
    set [ // Add current set to the set of subsets
          yield s
          // Remove each element and generate subset of 
          // that smaller set
          for e in s do
            yield! subsets (Set.remove e s) ]

// Sample usage
Set.subsets (set [1 .. 3])

但是,我想使用简单的列表,而不是模块集。如何使用可能使用列表理解的简单函数实现这一点?

您需要做的就是从原始列表中删除每个元素(一次一个),并生成结果列表,然后递归地对结果列表执行相同的操作:

let rec getSubLists l =
    [ yield l
      for x in l do
        let rest = l |> List.except [x]
        yield rest
        yield! getSubLists rest
    ] |> List.distinct
这将获得原始列表的所有不同子列表,包括空列表

getSubLists [1;2;3]

val it : int list list = [[1; 2; 3]; [2; 3]; [3]; []; [2]; [1; 3]; [1]; [1; 2]]

以下函数用于查找列表的所有子列表:

let rec powerset (xs: 'T list) : 'T list list =
    match xs with
    | [] -> [[]]
    | h::t -> List.fold (fun ys s -> (h::s)::s::ys) [] (powerset t)
对于集合,可以将集合转换为列表,调用此函数,然后再转换回集合列表:

let powerSet (s: Set<'T>) : Set<'T> list = 
    s
    |> Set.toList
    |> powerset
    |> List.map Set.ofList

> [0..2] |> Set.ofList |> powerSet;;
val it : Set<int> list =
  [set [0; 2]; set [2]; set [0; 1; 2]; set [1; 2]; set [0]; set []; set [0; 1];
   set [1]]
let powerSet(s:Set list=
s
|>托利斯特酒店
|>动力装置
|>List.map Set.of列表
>[0..2]|>列表集|>功率集;;
val it:设置列表=
[集[0;2];集[2];集[0;1;2];集[1;2];集[0];集[];集[0;1];
集合[1]]