smlmlunbound

What is causing my SML variables to be unbound?


I am very new to SML code and I am trying to make a function that returns a list of all prime numbers up to the number that is given by the user. I have most of the functions working except I keep getting an unbound variable or constructor error on my number, index, and lst variables. The code should use two helper functions to run through two indexs and multiply them getting non prime numbers out of the list. Here is my code:


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

Solution

  • Reindenting the code gives something like this:

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

    Some of the expressions are not part of the functions at all, which is why the parameters are not in scope. You can actually have multiple expressions in an else like this:

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

    But this will not work in your case because helpertwo does not have a side effect, so the real fix will be to use the result of helpertwo in some way.