Reputation: 2849
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.
Upvotes: 1
Views: 725
Reputation: 370102
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 to appendtolist
recursively within its definition.
Upvotes: 1
Reputation: 1209
To call the function recursively, you need to define it with let rec appendtolist
rather than just let appendtolist
.
You will then get a different error, because there are other bugs in your code ...
Upvotes: 2
Reputation: 118865
I don't know SML well, but I think you need some more parens, e.g.
else ((append-to-code n List.hd list) ^ (append-to-list n List.tl list) )
should be
else ((append-to-code n (List.hd list)) ^ (append-to-list n (List.tl list)) )
Upvotes: 0