问题
I'm suppose to write a function that copies elements in a array from one place to the other. copy_obj is the function doing that. now I am given a list of pointers that represents the locations of elements i need to copy therefore I need to apply the function copy_obj on each elements in the list with the address of the free location where I should start to copy. In my code it is f.
Considering that the function copy_obj returns a pair of addresses, and one is the updated value of free, I need to use to call recursively the function on other elements on the list.
below is the code I wrote, it compiles but I'am having a warning at | h::tl -> copy_obj f h saying this "expression should have type unit"
what can I do to arrange that?
let rec funct f myList =
match myList with
| [] -> f
| h::tl->
copy_obj f h;
match (copy_obj f h) with
| (free_n,addr_n) -> funct free_n tl
回答1:
You seem to be another student writing Copy GC. :-)
Expression e1; e2 is to execute e1 and e2 sequentially, and normally e1's return type is expected to be unit, which means "returns nothing special". If e1 is an expression whose type is other than unit, OCaml compiler emits a warning: "expression should have type unit", since it is possible that you compute something meaningful by e1 but you throw it away. It is sometimes a good indication of possible bugs.
In your case, copy_obj f h returns a tuple, probably (int * int), and it is not unit. Therefore you got the warning. If you really ok to discard the compuation result you must write ignore (copy_obj f h), where ignore : 'a -> unit.
You called copy_obj f h twice, which seems very strange. Without the definition of the function we cannot tell 100% sure but I guess you do not need the first call:
let rec funct f myList =
match myList with
| [] -> f
| h::tl->
match copy_obj f h with
| (free_n,addr_n) -> funct free_n tl
If you are implementing Copy GC and if copy_obj copies an object h to a free slot somewhere available using side effect, calling the function twice here stores h twice. It would be a serious bug for a GC algorithm. And the warning actually tries to help you at this exact point!!
One more thing. match is not the only way to deconstruct your value. let can also extract the elements of your tuple. Normally we write like:
let rec funct f myList =
match myList with
| [] -> f
| h::tl->
let (free_n, addr_n) = copy_obj f h in
funct free_n tl
Or you can simply write funct (fst (copy_obj f h)) tl.
来源:https://stackoverflow.com/questions/27417880/how-to-pattern-match-execute-a-function-then-pattern-match-on-the-executed-func