问题
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