一千萬個為什麽

搜索

F#:如何找到笛卡爾的力量

編寫笛卡爾冪函數時遇到問題。我發現了許多關於計算笛卡爾積的例子,但沒有關於笛卡爾冪的例子 例如,[1; 2]上升到冪3 = [[1; 1; 1]; [1; 1; 2]; [1; 2; 1]; [1; 2; 2]; [2; 1; 1]; [2; 1; 2]; [2; 2; 1]; [2; 2; 2]]
我使用以下代碼來計算笛卡爾積:

 let Cprod U V =
        let mutable res = []
        for u in U do
            for v in V do
                res <- res @ [[u;v]]
        res

並試圖計算笛卡爾的力量。 我使用以下代碼來計算笛卡爾積:

let Cpower U n =
    let mutable V = U
    for i=0 to n-1 do
        V <- Dprod U V
    V

Visual Studio說:錯誤在統一''a'和''列表'時,結果類型將是無限的。我會感謝任何幫助和鏈接。

最佳答案

至於錯誤的來源,我們有以下類型約束

// Cprod: seq<`a> -> seq<`a> -> `a list list
let Cprod U V =
    ...

// Cpower: seq<`a> -> int -> ???
let Cpower U n =
   //V: seq<`a>
    let mutable V = U
   //n: int
    for i=0 to n-1 do
        (* The next line implies two type constraints:
           V: seq<`a>
           V: `a list list *)
        V <- Dprod U V
    V

That V must be an seq<`a> and an `a list list, and that U and V must have the same type means that `a = `a list, which is what results in the "infinite type" error message (the infinity type is ... list list list list. Even though the value of V is mutable, it must have a single type.

轉載註明原文: F#:如何找到笛卡爾的力量