笛卡爾的生產有一個足夠好的功能 - 序列其定義這樣的:更不穩定序列比「經典」
let rec sequence = function
| [] -> Seq.singleton []
| (l::ls) -> seq { for x in l do for xs in sequence ls do yield (x::xs) }
但看看它的結果:
序列[[1..2]; [1..10000]] |> Seq.skip 1000 ;; val it:seq = seq [[1; 1001]; [1; 1002]; [1; 1003]; [1; 1004]; ...]
正如我們所看到的第一個「座標」的產品改變非常緩慢,當第二列表結束它會改變的值。
我寫了如下(下面的評論)我自己的序列:
/// Sum of all producted indeces = n
let rec hyper'plane'indices indexsum maxlengths =
match maxlengths with
| [x] -> if indexsum < x then [[indexsum]] else []
| (i::is) -> [for x in [0 .. min indexsum (i-1)] do for xs in hyper'plane'indices (indexsum-x) is do yield (x::xs)]
| [] -> [[]]
let finite'sequence = function
| [] -> Seq.singleton []
| ns ->
let ars = [ for n in ns -> Seq.toArray n ]
let length'list = List.map Array.length ars
let nmax = List.max length'list
seq {
for n in [0 .. nmax] do
for ixs in hyper'plane'indices n length'list do
yield (List.map2 (fun (a:'a[]) i -> a.[i]) ars ixs)
}
的核心思想是在(二)名單看起來在(二)正交的維度,每一個元素標誌着其在指數名單。所以我們可以枚舉所有元素,通過枚舉每個笛卡兒積的每個元素的超平面(在2D情況下,這是一條線)。換句話說,想象一下excel的表格,其中第一列包含[1; 1]到[1; 10000]的值,其次是從[2; 1]到[2; 10000]。編號爲1的「超平面」是連接單元格A2和單元格B1的線。對於我們的例子
hyper'plane'indices 0 [2; 10000] ;; val it:int list list = [[0; 0]]
hyper'plane'indices 1 [2; 10000] ;; val it:int list list = [[0; 1]; [1; 0]]
hyper'plane'indices 2 [2; 10000] ;; val it:int list list = [[0; 2]; [1; 1]]
hyper'plane'indices 3 [2; 10000] ;; val it:int list list = [[0; 3]; [1; 2]]
hyper'plane'indices 4 [2; 10000] ;; val it:int list list = [[0; 4]; [1; 3]]
那麼如果我們有的indeces和數組,我們從給定的列表產生比我們現在可以定義序列爲{平面0中的所有元素;比平面1中的所有元素...等等}並且獲得比原始序列更多的易失性函數。
但是有限'序列變成了非常貪吃的功能。現在是問題。我如何改進它?
祝福亞歷山大。 (對於英語不好的人,很抱歉)
我不知道我跟着你想要做什麼,而是你有沒有考慮使用簡單的笛卡爾函數預填充數組,然後做該數組中提取子序列/模式上的索引查找你要?似乎可能會更簡單。 – Daniel 2012-07-11 15:15:13
我想簡化一下。我想徹底擺脫陣列。請(爲簡潔起見)對@toyvo發表評論。預填充並不總是可能的。在我的情況下,很容易得到10個數組,每個元素都有1e5個元素作爲笛卡爾生產的參數。我正在做的事情的好例子(不是很有效)可能是_quickcheck_-like生成器。你用1000個符號取10個wchar數組,並嘗試製作長度爲10的字符串。我對C#解決方案有想象力,但我希望有更多或更少的簡潔功能。所以我嘗試。如果您有任何想法或建議,請在gmail.com免費發送電子郵件*我。 Tnx – 2012-07-12 08:19:42
@ alexander.vladislav.popov啊,所以你的應用程序是* quickcheck *。這意味着你可以使用隨機抽樣?這可能會大大減少你的宇宙。還是你想做詳盡的測試? – t0yv0 2012-07-12 20:36:45