The problem is best seen as a matrix problem, and nested loops βforβ an imperative solution can be performed functionally.
let Permute n = let rec Aux (x,y) = if (x,y) = (n,n) then [] else let nextTuple = if y = n then ((x + 1),1) else (x,(y + 1)) if x = y then Aux nextTuple else (x,y)::(Aux nextTuple) Aux (1,1)
This is not tail recursion, so the stack overflow at n = 500 on my machine. It is almost trivial to make this function tail recursive.
The time for this was very interesting. This function (tail recursive version) is 50% larger than the original, and the imperative solution took about 3 times more! Yes - the initial functional solution is the fastest, this is the next fastest, and understanding the imperative list was the slowest, at about 1 :: 1,5 :: 4. Tested on a variety of data sets.
source share