Calculating permutations in F#

后端 未结 7 1773
别跟我提以往
别跟我提以往 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:47

    If you need distinct permuations (when the original set has duplicates), you can use this:

    let rec insertions pre c post =
        seq {
            if List.length post = 0 then
                yield pre @ [c]
            else
                if List.forall (fun x->x<>c) post then
                    yield pre@[c]@post
                yield! insertions (pre@[post.Head]) c post.Tail
            }
    
    let rec permutations l =
        seq {
            if List.length l = 1 then
                yield l
            else
                let subperms = permutations l.Tail
                for sub in subperms do
                    yield! insertions [] l.Head sub
            }
    

    This is a straight-forward translation from this C# code. I am open to suggestions for a more functional look-and-feel.

    0 讨论(0)
提交回复
热议问题