Calculating permutations in F#

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

    Take a look at this one:

    http://fsharpcode.blogspot.com/2010/04/permutations.html

    let length = Seq.length
    let take = Seq.take
    let skip = Seq.skip
    let (++) = Seq.append
    let concat = Seq.concat
    let map = Seq.map
    
    let (|Empty|Cons|) (xs:seq<'a>) : Choice> =
        if (Seq.isEmpty xs) then Empty else Cons(Seq.head xs, Seq.skip 1 xs)
    
    let interleave x ys =
        seq { for i in [0..length ys] ->
                (take i ys) ++ seq [x] ++ (skip i ys) }
    
    let rec permutations xs =
                match xs with
                | Empty -> seq [seq []]
                | Cons(x,xs) -> concat(map (interleave x) (permutations xs))
    

提交回复
热议问题