【发布时间】:2013-06-26 16:43:40
【问题描述】:
我正在尝试在 SML 中编写一个函数,该函数接受一个整数列表并输出一个有序整数对列表。有序对第一个 int 是输入列表中出现的 int,有序对中的第二个 int 是它在输入列表中出现的次数。此外,返回的列表应根据有序对中的第一个 int 升序排列。
例如输入列表[1, 1, 1, 2, 3, 3, 5] 将输出为[(1,3), (2, 1), (3, 2), (5, 1)]。
到目前为止,我有一个使用foldl的函数
更新自原始帖子以来的代码。
fun turnIntoPairs l = foldl (fn (e, a) => if List.exists (fn (x, _) => x = e) a then x + 1 else a @ [(e, 1)]) [] l;
我在更新列表时遇到了问题,在该列表中找到了已在列表中的有序对 - 我想将一个添加到已在列表中找到的有序对中的第二个 int。
任何帮助将不胜感激!
C:\Program Files (x86)\SMLNJ\\bin\.run\run.x86-win32.exe: Fatal error -- Uncaught exception Error with 0
raised at ../compiler/TopLevel/interact/evalloop.sml:66.19-66.27
[autoloading done]
C:\Users\Localadmin\Desktop\CS 671\Program 3\commonFactors.sml:1.87 Error: unbound variable or constructor: x
C:\Users\Localadmin\Desktop\CS 671\Program 3\commonFactors.sml:1.44-1.110 Error: types of if branches do not agree [literal]
then branch: int
else branch: (''Z * int) list
in expression:
if (List.exists (fn <pat> => <exp>)) a
then <errorvar> + 1
else a @ (e,1) :: nil
[Finished in 0.5s with exit code 1]
【问题讨论】:
-
看看你的错误。它抱怨
find和x不存在。find我认为您的意思是List.find,尽管该类型签名与您尝试提供的参数不符。 -
另外,同样的问题正在回答here
-
我看到了那个帖子,我在写这个问题的时候那个帖子发了。我使用这些信息开始编写这个我现在遇到问题的函数。
-
所以我摆脱了存在,因为这不是我想要做的。我试图查看列表中是否有一对 (e, _)。我在问题帖子中更新了我当前的功能。
if List.exists (fn (x, _) => x = e) a then ....部分是否适合我想要完成的任务?
标签: list recursion functional-programming sml smlnj