how to pattern match, execute a function then pattern match on the executed function to execute another function

余生长醉 提交于 2019-12-12 06:37:02

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!