【问题标题】:Recursive function to calculate permutations in F# has type mismatch error在 F# 中计算排列的递归函数存在类型不匹配错误
【发布时间】: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


    【解决方案1】:

    假设你的函数的缩进是正确的,错误信息是非常有用的。在innerLoop 函数中,Array.append firstPart secondPart 应该返回'b []。但是,最后一行Array.map(fun d -&gt; innerLoop (fst d) (snd d)) 强制返回'b [] [],不能与'b [] 统一。

    我认为您想计算每个 innerLoop 中的排列,然后将这些结果连接起来。你必须使用Array.collect 而不是Array.map:

    [|for i in 0 .. (Array.length secondPart)-1 -> i|] 
    |> Array.map (fun c -> SliceAtMarkerElement c) 
    |> Array.collect (fun d -> innerLoop (fst d) (snd d))
    

    上面的片段使用了两个临时数组,很浪费。您可以仅使用计算表达式来消除这些额外的数组:

    [| for i in 0 .. (Array.length secondPart)-1 do
          let first, second = SliceAtMarkerElement i
          yield! innerLoop first second (* concatenating results *)
        |]
    

    更新:

    正如评论中所阐明的,您希望返回一个数组数组,其中每个数组都是一个排列。所以你的改变会起作用,map 操作应该是:

    [| for i in 0 .. (Array.length secondPart)-1 do
              let first, second = SliceAtMarkerElement i
              yield innerLoop first second (* returning each array as a permutation *)
            |]
    

    【讨论】:

    • 是的。收集作品。但它是将所有元素扁平化为一个元素数组。我想要的是一个数组数组,其中每个数组都是元素的排列。为此,我需要更改递归退出条件以返回 [| Array.Append firstPart SecondPart |]。我已经用一些索引绑定修复更新了这个问题。
    猜你喜欢
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多