【发布时间】:2012-01-27 06:02:15
【问题描述】:
我正在尝试在 F# 中编写一个通用函数,该函数将返回列表的所有排列。我试图使用受 java 版本 here 启发的递归算法来实现这一点
但是在递归函数的最后一行,我得到了 cmets 中给出的错误。我猜这与将递归循环退出时产生的输出(正在执行的 if(Array.length <= 1) then 的输出)与其余的 Array.Map 函数进行比较有关。
如果有人能解释为什么会发生这个错误以及我该如何解决它,我将不胜感激。
let GetPermutationsOfList inputList =
let rec innerLoop firstPart secondPart =
if (Array.length secondPart) <= 1 then
[| Array.append firstPart secondPart |]
else
let SliceAtMarkerElement m =
let currentMarkerElement = secondPart.[m]
let everythingBeforeMarkerElement = secondPart.[0 .. m - 1]
let everythingAfterMarkerElement = secondPart.[m+1 .. ]
let newSecondPartList = Array.append everythingBeforeMarkerElement everythingAfterMarkerElement
let newFirstPartList = Array.append firstPart [|currentMarkerElement|]
(newFirstPartList, newSecondPartList)
[|for i in 0 .. ((Array.length secondPart) - 1) -> i|] |>
Array.map(fun c -> SliceAtMarkerElement c) |>
// The following line gives the error
// "Type Mismatch. Expecting a 'a but given a 'a[] The resulting type would be infinite when unifying "a' and "a[]"
Array.map(fun d -> innerLoop (fst d) (snd d))
innerLoop Array.empty (List.toArray inputList)
【问题讨论】:
标签: recursion f# functional-programming permutation