Calculating permutations in F#

后端 未结 7 1775
别跟我提以往
别跟我提以往 2020-11-30 07:46

Inspired by this question and answer, how do I create a generic permutations algorithm in F#? Google doesn\'t give any useful answers to this.

EDIT: I provide my be

7条回答
  •  失恋的感觉
    2020-11-30 08:42

    If you need permutations with repetitions, this is the "by the book" approach using List.indexed instead of element comparison to filter out elements while constructing a permutation.

    let permutations s =
        let rec perm perms carry rem =
            match rem with
                | [] -> carry::perms
                | l ->
                    let li = List.indexed l
                    let permutations =
                            seq { for ci in li ->
                                    let (i, c) = ci
                                    (perm
                                            perms
                                            (c::carry)
                                            (li |> List.filter (fun (index, _) -> i <> index) |> List.map (fun (_, char) -> char))) }
    
                    permutations |> Seq.fold List.append []
        perm [] [] s
    

提交回复
热议问题