首页 > 解决方案 > 是什么导致我的 SML 变量未绑定?

问题描述

我对 SML 代码非常陌生,我正在尝试创建一个函数,该函数返回所有素数的列表,直到用户给出的数字。除了我的数字、索引和 lst 变量不断出现未绑定变量或构造函数错误外,我的大多数函数都在工作。代码应该使用两个辅助函数来遍历两个索引并将它们相乘,从而将非素数从列表中取出。这是我的代码:


fun removeMult (lst,n) = if null lst then lst else if hd lst mod n = 0 then removeMult(tl lst, n) else (hd lst) :: removeMult(tl lst, n);

fun helpertwo(lst, ind : int, n : int, indtwo : int) = if indtwo = n then lst else helpertwo(removeMult(lst , ind*indtwo),ind,n,indtwo+1);

fun test(lst,number,index) = 
if 
 number = index 
then 
 lst 
else
 helpertwo(lst, index, number, 2);
 test(lst,number,(index+1));

fun primes (n : int) = 
if 
 (n <= 1)
then
 []
else
  makelist(n);
  removeMult(lst , 1);
  test(lst, n , 2);

标签: smlmlunbound

解决方案


重新缩进代码给出了这样的结果:

fun test(lst,number,index) = 
    if 
    number = index 
    then 
    lst 
    else
    helpertwo(lst, index, number, 2);
test(lst,number,(index+1));

fun primes (n : int) = 
    if 
    (n <= 1)
    then
    []
    else
    makelist(n);
removeMult(lst , 1);
test(lst, n , 2);

有些表达式根本不是函数的一部分,这就是为什么参数不在范围内的原因。实际上,您可以像这样有多个表达式else

    else
    (helpertwo(lst, index, number, 2);
     test(lst,number,(index+1)))

但这在您的情况下不起作用,因为helpertwo没有副作用,所以真正的解决helpertwo方法是以某种方式使用结果。


推荐阅读