尝试获取列表中偶数和奇数整数的数量

问题描述 投票:0回答:1

我正在尝试编写一个递归函数,它接受列表作为参数并返回元组中偶数和奇数的数量(偶数,奇数)

let rec countEvenOdd lst e o =
  match lst with
  | [] -> (e,o) (* Base case: empty list *)
  | hd :: tl -> if hd mod 2 = 0 then countEvenOdd tl (e + 1) o else countEvenOdd tl e (o + 1)
;;

countEvenOdd [2;4;5;6;7;8];;

这只是给了我类型推断

  • :int -> int -> int * int =
list recursion functional-programming ocaml
1个回答
0
投票

因为您向需要三个参数的函数提供了一个参数,所以您已经部分应用了该函数,因此您得到了一个函数,该函数接受剩余的两个参数。

毫无疑问,您打算调用

countEvenOdd [2; 4; 5; 6; 7; 8] 0 0
,但您可以通过隐藏
countEvenOdd
来隐藏该实现细节。

let rec countEvenOdd lst e o =
  match lst with
  | [] -> (e,o) (* Base case: empty list *)
  | hd :: tl -> 
    if hd mod 2 = 0 then countEvenOdd tl (e + 1) o 
    else countEvenOdd tl e (o + 1)

let countEvenOdd let = countEvenOdd lst 0 0
© www.soinside.com 2019 - 2024. All rights reserved.