Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most elegant combinations of elements in F#

One more question about most elegant and simple implementation of element combinations in F#.

It should return all combinations of input elements (either List or Sequence). First argument is number of elements in a combination.

For example:

comb 2 [1;2;2;3];;
[[1;2]; [1;2]; [1;3]; [2;2]; [2;3]; [2;3]]
like image 511
The_Ghost Avatar asked Aug 03 '09 12:08

The_Ghost


2 Answers

One less concise and more faster solution than ssp:

let rec comb n l = 
    match n, l with
    | 0, _ -> [[]]
    | _, [] -> []
    | k, (x::xs) -> List.map ((@) [x]) (comb (k-1) xs) @ comb k xs
like image 115
The_Ghost Avatar answered Nov 16 '22 01:11

The_Ghost


let rec comb n l =
  match (n,l) with
  | (0,_) -> [[]]
  | (_,[]) -> []
  | (n,x::xs) ->
      let useX = List.map (fun l -> x::l) (comb (n-1) xs)
      let noX = comb n xs
      useX @ noX
like image 38
kvb Avatar answered Nov 16 '22 03:11

kvb