组合两个流,从一个然后另一个拉动元素

时间:2017-02-14 09:13:07

标签: sml

鉴于这些声明,我无法理解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]

1 个答案:

答案 0 :(得分:3)

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

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))))