F# permutations

后端 未结 6 646
予麋鹿
予麋鹿 2020-12-08 17:34

I need to generate permutations on a given list. I managed to do it like this

let rec Permute (final, arr) = 
    if List.length arr > 0 then
        for          


        
6条回答
  •  离开以前
    2020-12-08 17:50

    It depends on what you mean by "better". I'd consider this to be slightly more elegant, but that may be a matter of taste:

    (* get the list of possible heads + remaining elements *)
    let rec splitList = function
    | [x] -> [x,[]]
    | x::xs -> (x, xs) :: List.map (fun (y,l) -> y,x::l) (splitList xs)
    
    let rec permutations = function
    | [] -> [[]]
    | l -> 
        splitList l 
        |> List.collect (fun (x,rest) ->
             (* permute remaining elements, then prepend head *)
             permutations rest |> List.map (fun l -> x::l))
    

    This can handle lists with duplicate elements, though it will result in duplicated permutations.

提交回复
热议问题