SMLNJ报错:type constructor list参数不匹配,新手求助修复及实数转整数方法
Let's break down your problems step by step:
Fixing the Type Error
The error Error: type constructor list given 0 arguments, wants 1 happens because in Standard ML, list is a parameterized type — it requires you to specify what kind of elements it holds (like int list or real list). Your code uses lista:list and result:list without defining their element types, which confuses the type checker.
There are a couple other issues in your code to fix too:
- The
gcdfunction typically takes two integers, but you're passing an entire list and arealvalue. Assuming you want the greatest common divisor of the current list element andlcm_wi, you should pass the single element (not the whole list). Nis an unbound variable here — unless you've defined it elsewhere, you should uselength listato get the size of the input list instead.
Here's a revised version of your code (assuming Rate is a real list, and we define a helper function for real-number GCD since standard gcd works with integers):
(* Helper function to calculate GCD of two real numbers *) fun real_gcd (x: real, y: real): real = if Real.==(y, 0.0) then x else real_gcd (y, x - Real.fromInt(Real.floor(x/y)) * y); fun without_i (num:int) (lista:real list) (result:real list) (lcm_wi:real) = if num >= length lista - 1 then result else let val b = List.nth(lista, num) val a = real_gcd(b, lcm_wi) in without_i (num+1) lista (lcm_wi :: result) ((b/a)*lcm_wi) end; val before_i_rev = without_i 0 Rate [] 1.0;
Converting REAL to INT
Standard ML provides several built-in functions to convert real values to int, each with different rounding behavior:
Real.trunc: Truncates the decimal part (rounds towards zero) — e.g.,Real.trunc 3.7 = 3,Real.trunc ~3.7 = ~3Real.floor: Rounds down to the nearest integer — e.g.,Real.floor 3.7 = 3,Real.floor ~3.7 = ~4Real.ceil: Rounds up to the nearest integer — e.g.,Real.ceil 3.2 = 4,Real.ceil ~3.2 = ~3Real.round: Rounds to the nearest integer (standard rounding) — e.g.,Real.round 3.4 = 3,Real.round 3.5 = 4
Example usage:
val rounded = Real.round 5.6; (* Evaluates to 6 *) val truncated = Real.trunc 7.9; (* Evaluates to 7 *)
Note: If the real value is outside the valid range for int, this will cause a runtime error, so make sure your values are within bounds before converting.
内容的提问来源于stack exchange,提问作者Celia

