【问题标题】:combining two streams, pulling element from one then other结合两个流,从一个然后另一个拉元素
【发布时间】:2017-02-14 18:01:38
【问题描述】:

鉴于这些声明,我无法理解 SML 中的流:

exception Bad of string;
fun from seed next = Cons(seed,fn () => from (next seed) next);
fun head (Nil) = raise Bad("got nil in head")
    | head (Cons(a,b)) = a;

fun tail (Nil) = raise Bad("got nil in tail") 
    | tail(Cons(a,b)) = b();

fun take 0 stream = nil
    | take n (Nil) = raise Bad("got nil in take")
    |take n (Cons(h,t)) = h::(take (n-1) (t()));

我可以像这样创建一个自然流 [1.0,2.0,3.0...]:val nat = from 1.0 (fn x => x+1.0);

还有一个流:val one = from 1.0 (fn x => x);

但是我将如何从这两个流创建一个流?特别是合并两个流并输出一个流的函数。

类似:fun merge a b 其中 a 和 b 是流。即,如果我们在合并这两个之后执行take 5,它将得到 [1.0,1.0,2.0,1.0,3.0]

【问题讨论】:

    标签: sml


    【解决方案1】:

    如果这是一个列表,你会写

    fun merge a b = Cons (head a, Cons (head b, merge (tail a) (tail b)))
    

    然后你为每个缺点添加一个函数间接来“流化”它:

    fun merge a b = Cons (head a, fn () => Cons (head b, fn () => (merge (tail a) (tail b))))
    

    【讨论】:

      猜你喜欢
      • 2018-03-08
      • 1970-01-01
      • 2016-07-06
      • 2011-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      • 1970-01-01
      相关资源
      最近更新 更多