我正在尝试使用 SML 来执行以下操作:
val nextInt = Random.randRange (1,50);
val r = Random.rand ();
val x1 = nextInt r;
val x2 = nextInt r;
val inputL = [(x1,1)];
然后,我需要将此列表加载到输入列表中,并逐个处理列表元组,以便如果之前未见过第一个值,则会将其添加到输出列表中。如果已经看到,则增加 2 变量(第二个变量表示看到该数字的频率)
接下来是按第一个整数的升序自动对输出列表进行排序。
我很迷茫...本质上这个程序可能会循环10次,为第一个整数提供一个随机int,第二个整数为频率,然后按升序排列第一个变量。
我再次尝试过这个,它只给了我一个由 1 个随机整数和一个 1 组成的元组。我需要它循环大约 10 次,跟踪频率并对其进行排序。
val nextInt = Random.randRange (1,50);
val r = Random.rand ();
val x1 = nextInt r;
val x2 = nextInt r;
val inputL = [(x1,1)];
输出即时消息:
> val r = <rand>: Random.rand;
> val x1 = 2: int;
> val x2 = 3: int;
> val inputL = [(2, 1)]: (int * int) list;
您的描述不是很清楚,但似乎您正在尝试统计元组列表。让我们跳过有关生成随机整数列表的部分,仅使用一个示例。
val numbers = [10, 45, 5, 32, 10, 2, 17, 22, 38, 17]
简单的方法将涉及两个更简单的操作:计算列表中的值,以及从列表中过滤值。两者都可以轻松实现为递归函数。
fun count _ [] = 0
| count v (x::xs) =
(if x = v then 1 else 0) + count v xs;
fun filter _ [] = []
| filter v (x::xs) =
if x = v then
filter v xs
else
x :: filter v xs;
那么理货的基本规则就非常简单了:
示例运行可能如下所示:
tally [10, 45, 5, 32, 10, 2, 17, 22, 38, 17]
(10, 2) :: tally [45, 5, 32, 2, 17, 22, 38, 17]
(10, 2) :: (45, 1) :: tally [5, 32, 2, 17, 22, 38, 17]
(10, 2) :: (45, 1) :: (5, 1) :: tally [32, 2, 17, 22, 38, 17]
(10, 2) :: (45, 1) :: (5, 1) :: (32, 1) :: tally [2, 17, 22, 38, 17]
(10, 2) :: (45, 1) :: (5, 1) :: (32, 1) :: (2, 1) :: tally [17, 22, 38, 17]
(10, 2) :: (45, 1) :: (5, 1) :: (32, 1) :: (2, 1) :: (17, 2) :: tally [22, 38]
(10, 2) :: (45, 1) :: (5, 1) :: (32, 1) :: (2, 1) :: (17, 2) :: (22, 1) :: tally [38]
(10, 2) :: (45, 1) :: (5, 1) :: (32, 1) :: (2, 1) :: (17, 2) :: (22, 1) :: (38, 1) :: tally []
(10, 2) :: (45, 1) :: (5, 1) :: (32, 1) :: (2, 1) :: (17, 2) :: (22, 1) :: (38, 1) :: []
[(10, 2), (45, 1), (5, 1), (32, 1), (2, 1), (17, 2), (22, 1), (38, 1)]
这具有非常差的运行时复杂性,因为它涉及循环内的循环。考虑如果列表被排序first,统计列表是否会更容易。