简体   繁体   English

带字符列表的OCaml对int

[英]OCaml pair int with char list

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> . 我正在使用原型remaining thelist需要val remaining : char list -> int * char list = <fun>签名val remaining : char list -> int * char list = <fun>的函数val remaining : char list -> int * char list = <fun> remaining thelist 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. 我是Ocaml的新手,我不明白如何使Ocaml函数仅接受一个列表,并同时输出一个int和一个列表。 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. 如果您注释掉第一个块,则第二个块将输出正确的int。 I have no clue on how to combine the code to achieve the desired signature without some kind of compatibility error. 我不知道如何组合代码以实现所需的签名而不会出现某种兼容性错误。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM