如何在 SML/NJ 中递归地制作一个随机填充的列表

How to make a randomly populated list recursively in SML/NJ

fun randomList(n) =  let 
    val theList = []
    val min = 1
    val max = 75
    val nextInt = Random.randRange(min,max)
    val r = Random.rand(1,1)
    val randomValue = nextInt r
    in  
    if n = 0 then [] 
    else 
    (randomValue::theList;
    randomList(n-1)) end;

randomList(50); 

I'm trying to populate a list with random numbers. I'm getting the error Warning: type vars not generalized because of value restriction are instantiated to dummy types (X1, X2,...) I've seen some different possible reasons for this but I can't figure it out. What do I need to change? I'm still not sure that the function even works because I haven't been able to fully run it.

你给出的函数是给出类型:

val randomList = fn : int -> 'a list

那么问,为什么 then 'a 不泛化为 int? 让我们看看 else 分支中的表达式。

- val foo = ({}; 5);
val foo = 5 : int

表达式(e1;e2)求值e1,然后求值andreturns e2, 丢弃 e1 的结果。从那里开始,它应该开始理解为什么 returning 一个 列表 .

  1. theList 移动到参数。
  2. 添加一个传递空列表的辅助函数。
  3. 在累积所有随机数后返回theList
  4. 正如您在评论中指出的那样,它有助于提取随机种子 r 到辅助函数的参数,因此随机数生成器不会生成继续生成相同的数字。

    我们仍然对 randomList 的每次调用使用相同的初始种子,因此相同长度的每次调用都将 return 相同的列表。 可以在这里找到更好的种子函数:

fun randomList (n) =
 let fun helper (n, s) theList =
  if n = 0
     then theList
     else
      let val min = 1
          val max = 75
          val nextInt = Random.randRange(min,max)
          val randomValue = nextInt s
       in helper (n - 1, s) (randomValue::theList)
      end;
 in helper (n, Random.rand(1, 1)) [] end;