【问题标题】:merging 2 lazy lists type conflict合并 2 个惰性列表类型冲突
【发布时间】:2017-03-09 11:43:07
【问题描述】:

为什么我的merge 函数抱怨它的类型?

我的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 不起作用。

谢谢。

【问题讨论】:

    标签: ocaml lazy-evaluation lazy-sequences


    【解决方案1】:

    只需写(_ 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 ()))
    

    【讨论】:

      猜你喜欢
      • 2018-05-07
      • 1970-01-01
      • 2017-01-28
      • 2021-01-20
      • 2013-03-24
      • 2019-09-01
      • 2018-03-28
      • 2019-10-18
      • 2015-04-10
      相关资源
      最近更新 更多