2017-02-15 7 views
2
datatype 'a stream = 
    Nil 
    | Cons of 'a * (unit -> 'a stream); 

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 (h, t)) = h; 

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

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

私は無限階乗ストリームを書こうとしています。無限階乗ストリームは2つのストリームをとり、1つのストリームを出力します。ファクトリ・ストリームSML

fun fac(a,b) = Cons(a, fn() => fac(b, a*(b-1)); 

これまで私がこれまで行ってきたことです。しかし、それは私に正しい答えを与えるものではありません。

+0

SMLは、ストリームの任意の組み込みの概念を持っていません。無限階乗の流れとは何か、それは2つの流れの関数であるとはどういう意味ですか? 「短所」とは何ですか?あなたの質問を明確にしてください。 –

+0

あなたは何を期待するか?あなたはそれをデバッグしようとしましたか? – Carcigenicate

答えて

2

factorialsが特定のシーケンスを形成するので、factorialストリームが入力を受け取ることは意味がないと思います。 (!Nとn

は代わりに、あなたは内部の状態を管理するヘルパー関数を必要とし、その後、ストリーム自体は単なる値である。また

local 
    (* returns a stream consisting of 
     nFac, 
     nFac * nextN, 
     nFac * nextN * (nextN + 1), 
     nFac * nextN * (nextN + 1) * (nextN + 2), 
     ... 
    *) 
    fun facHelper (nFac, nextN) = Cons (nFac, fn() => facHelper (nFac * nextN, nextN + 1)) 
in 
    (* a stream consisting of 0!, 1!, 2!, 3!, ... *) 
    val factorials = facHelper (1, 1) 
end 

、あなたが作成することができます番号1のストリーム、2、3、&hellip ;,及びストリームS与えられ、ストリーム減速は、S 1 0、1、S のストリームを返しますSSSS 、&hellip ;:

local 
    (* returns a stream consisting of n, n + 1, n + 2, n + 3, ... *) 
    fun positiveIntegersHelper n = Cons (n, fn() => positiveIntegersHelper (n + 1)) 
in 
    (* a stream consisting of 1, 2, 3, 4, ... *) 
    val positiveIntegers = positiveIntegersHelper 1 
end 

(* Note: the above could also have been written using your 'from' function, as 
     val positiveIntegers = from 1 (fn n => n + 1) 
*) 

(* given a function f, an initial value seed, and a stream consisting of [s1, s2, s3, ...], 
    returns a stream consisting of 
    [seed, f(s1, seed), f(s2, f(s1, seed)), f(s3, f(s2, f(s1, seed))), ...] 
    -- so, somewhat analogous to List.foldl, except that it returns a stream of all partial 
    results, instead of just the final result. 
*) 
fun reduceStream _ seed Nil = Cons (seed, fn() => Nil) 
    | reduceStream f seed (Cons (h, tf)) = 
     Cons (seed, fn() => reduceStream f (f (h, seed)) (tf())) 

(* a stream consisting of 0!, 1!, 2!, 3!, ... *) 
val factorials = reduceStream op* 1 positiveIntegers