SML变量未绑定问题求助:生成指定范围素数函数报错
Hey there! Let's work through fixing your SML prime sieve code step by step—those "unbound variable" errors are totally common when you're getting started with the language, so no need to stress.
First, let's break down why you're seeing those errors:
- You have global calls like
test(lst,number,(index+1));andremoveMult(lst , 1);wherelst,number, andindexaren't defined anywhere in the global scope. These calls shouldn't be floating outside of functions—all variable references need to be tied to a local or global definition. - Your
primesfunction referencesmakelist(n)but never defines that helper function, which is another gap in the logic.
Let's rewrite and fix your code while keeping your original approach of using two helper functions for sieving:
Corrected Full Code
(* Helper to create a list of integers from 2 up to n *) fun makelist(n : int) = let fun helper(current, acc) = if current < 2 then acc else helper(current - 1, current :: acc) in helper(n, []) end; (* Removes all multiples of n from a given list *) 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); (* Helper to sieve out multiples of ind * indtwo up to n *) fun helpertwo(lst, ind : int, n : int, indtwo : int) = if ind * indtwo > n then lst else helpertwo(removeMult(lst, ind * indtwo), ind, n, indtwo + 1); (* Main helper to iterate through each index for sieving *) fun test(lst, number, index) = if index * index > number then lst else test(helpertwo(lst, index, number, 2), number, index + 1); (* Main primes function that ties everything together *) fun primes(n : int) = if n <= 1 then [] else test(makelist(n), n, 2);
Key Fixes & Explanations
- Added the missing
makelistfunction: This generates the initial list of numbers from 2 ton—your originalprimesfunction called this but never defined it. The tail-recursive helper inside makes it efficient too. - Removed global variable calls: All function invocations now happen inside other functions, so every variable (like
lst,number,index) is properly bound to a local value. No more unbound variable errors! - Fixed termination conditions:
helpertwostops whenind * indtwoexceedsn(no need to sieve numbers larger than our target).teststops whenindex * indexexceedsn—this is a standard optimization for the Sieve of Eratosthenes, since any number larger than the square root ofnwill already have been sieved by smaller primes.
- Recursive flow in
test: Your originaltestonly ranhelpertwoonce and returned. Now it recursively calls itself with an incremented index, ensuring we sieve for all relevant primes.
Quick Test
If you run primes(10); it should return [2,3,5,7], which is the correct list of primes under 10.
内容的提问来源于stack exchange,提问作者Jack Van Well
相关产品推荐
相关产品推荐

