错误 - 通过传递列表进行递归函数调用 - OCaml
我正在尝试创建 OCaml 列表中包含的字符串的排列。 到目前为止,我已经处理了以下代码片段,但面临将列表的第一个字符串传递给我的方法的问题。
代码逻辑: 迭代列表的每个元素并将每个元素附加到列表的元素。继续这样做,直到所有元素都已附加到列表中每个可能的位置。
代码:
(* this function appends each string to each word in the list example: "A" with "ABC" *)
let appendtocode n word =
let f x = n ^ x in
f word
;;
(* this function extracts every element of the list and appends it with the string.
Example: "A" with ["AAA","ABC","ACD"] etc.. *)
let appendtolist n list =
let f x =
if (List.length list) > 0 then list
else ((appendtocode n (List.hd list)) ^ (appendtolist n (List.tl list)) )
in
List.map f list
;;
错误:
我收到此错误:
未绑定值appendtolist
在调用时发生:(appendtolist n List.tl list)
我的列表仅由字符串组成。 我仍在编写代码。但由于这个错误而陷入困境。
请帮忙!!!任何输入都会很棒。
I am trying to create permutations of strings contained in a list in OCaml.
I have worked on the following snippet of code till now but am facing a problem passing the first string of the list to my method.
Logic for code:
Iterate to every element of a list and append each element with element of the list. Continue doing till all the elements have been appended to the list in every possible position.
Code:
(* this function appends each string to each word in the list example: "A" with "ABC" *)
let appendtocode n word =
let f x = n ^ x in
f word
;;
(* this function extracts every element of the list and appends it with the string.
Example: "A" with ["AAA","ABC","ACD"] etc.. *)
let appendtolist n list =
let f x =
if (List.length list) > 0 then list
else ((appendtocode n (List.hd list)) ^ (appendtolist n (List.tl list)) )
in
List.map f list
;;
Error:
I get this error:
Unbound value appendtolist
Occurs at call to : (appendtolist n List.tl list)
My list is only consisting of string.
I am still working on the code. But stuck at this because of this error.
Please help!!! Any input would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要递归地调用该函数,您需要使用
let recappendtolist
来定义它,而不仅仅是letappendtolist
。然后你会得到一个不同的错误,因为你的代码中还有其他错误......
To call the function recursively, you need to define it with
let rec appendtolist
rather than justlet appendtolist
.You will then get a different error, because there are other bugs in your code ...
您收到“未绑定值appendtolist”错误,因为您在递归调用
appendtolist
时未声明为递归。您需要编写
let recappendtolist n list = ...
才能在其定义中递归引用appendtolist
。You're getting the "Unbound value appendtolist" error because you're calling
appendtolist
recursively without declaring as recursive.You need to write
let rec appendtolist n list = ...
to be able to refer toappendtolist
recursively within its definition.我不太了解 SML,但我认为你需要更多的括号,例如
应该是
I don't know SML well, but I think you need some more parens, e.g.
should be