OCaml pair int with char list

放肆的年华 提交于 2019-12-24 19:05:19

问题


I'm working with a function with the prototype remaining thelist that needs to take on the signature val remaining : char list -> int * char list = <fun>. I'm new to Ocaml and I do not understand how to make an Ocaml function take in only a list and output both an int and a list. This is the code I'm currently working with.

let rec remaining thelist= match thelist with
  | [] -> []
  | [x] -> [x]
  | x::y::t1 ->
      if x='a' then remaining (y::t1)
      else thelist;;

match thelist with
  | [] -> 0
  | x::t1 -> 
    if x='a' then 1+remaining t1
    else 0;;

The first block of code outputs the correct char list if you comment out the second block. The second block outputs the correct int if you comment out the first block. I have no clue on how to combine the code to achieve the desired signature without some kind of compatibility error.


回答1:


You can use product type (in fact your signature advise you to do so) and 'hidden' local function

let remaining =
     let rec f i = function
       | 'a'::l -> f (i+1) l
       | l -> i, l
     in
     f 0


来源:https://stackoverflow.com/questions/45242865/ocaml-pair-int-with-char-list

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