阶乘流SML

阶乘流SML,sml,Sml,我正在尝试编写一个无限阶乘流,其中它接受两个流并输出一个流 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

我正在尝试编写一个无限阶乘流,其中它接受两个流并输出一个流

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

这就是我目前所拥有的。但是它没有给我正确的答案。

我认为阶乘流接受任何输入都没有意义,因为阶乘形成了一个特定的序列

相反,您需要一个帮助函数来管理内部状态(n和n!),然后流本身就是一个值:

fun fac(a,b) = Cons(a, fn() => fac(b, a*(b-1));
或者,您可以创建一个数字为1、2、3、…、的流,以及一个流减缩器,该减缩器在给定流s的情况下返回1、s1、s1s2、s1s2s3、…:


SML没有任何内置的流概念。什么是无限阶乘流?说它是两条流的函数是什么意思?什么是
Cons
?请澄清你的问题。它能给你带来什么?你试过调试它吗?
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
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