开发者

Error - Recursive function calls by passing lists - OCaml

开发者 https://www.devze.com 2023-01-27 01:11 出处:网络
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 m

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 ever开发者_运维问答y 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.


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 ...


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.


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)) ) 
0

精彩评论

暂无评论...
验证码 换一张
取 消