2017-03-09 74 views
1

爲什麼我的merge函數抱怨它的類型?合併2懶惰列表類型衝突

是不是我x一個type 'a seq

type 'a seq = Stop | Cons of 'a * (unit -> 'a seq) 

let rec linear start step= (*builds a seq starting with 'start'*) 
    Cons (start, fun() -> linear (start+step) step) 

let rec take n seq = match seq with (*take first n elem from seq*) 
| Stop -> [] 
| Cons (a, f) -> if n < 1 then [] else a::(take (n-1) (f())) 

let rec merge seq1 seq2 = match seq1, seq2 with 
    | Stop, _ -> seq2 
    | _, Stop -> seq1 
    | Cons(h1, tf1), _ as x -> 
     Cons(h1, fun() -> merge (x) (tf1())) 

let l1 = linear 1 1 
let l2 = linear 100 100 
let l3 = interleave l1 l2 

我想看到正確的結果爲

take 10 l3 

INT列表= [1; 100; 2; 200; 3; 300; 4; 400; 5; 500]

另一種方式來寫我的功能(工作)將

let rec merge seq1 seq2 = match seq1 with 
| Stop -> Stop 
| Cons (h, tf) -> Cons(h, fun() -> merge seq2 (tf())) 

,但我不明白,爲什麼第一次merge不起作用。

感謝。

回答

0

只要寫(_ as x)因爲在這裏,你as x捕獲整個模式。

因此,您所看到的是:

| Cons(h1, tf1), (_ as x) -> ... 

實際上被解析爲

| (Cons(h1, tf1), _) as x -> ... 

你實際上可以寫:

| Cons(h1, tf1), x -> ... 

這是好得;-)

甚至是

| Cons(h1, tf1), _ -> Cons(h1, fun() -> merge seq2 (tf1()))