带字符列表的OCaml对int

带字符列表的OCaml对int

本文介绍了带字符列表的OCaml对int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有原型remaining thelist的函数,该函数需要具有签名val remaining : char list -> int * char list = <fun>.我是Ocaml的新手,我不明白如何使Ocaml函数仅接受一个列表,并同时输出一个int和一个列表.这是我目前正在使用的代码.

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;;

如果您注释掉第二个块,则第一个代码块将输出正确的字符列表.如果您注释掉第一个块,则第二个块将输出正确的int.我不知道如何组合代码以实现所需的签名而不会出现某种兼容性错误.

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.

推荐答案

您可以使用产品类型(实际上,您的签名会建议您这样做)和隐藏"本地功能

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

这篇关于带字符列表的OCaml对int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 12:31