编写函数 residue l n ,通过迭代计算计算 n 与 l 的余数

Write the function residue l n which calculates the residue of n by l by making an iterative calculation

我想编写函数 residue l n,它通过从 n 开始并按顺序使用列表中的项目进行迭代计算来计算 n 与 l 的余数。计算如下: - 最初残差是 n 的值 - l 的每个元素 e(按列表的顺序)按以下方式更改残基: 如果 e 和余数具有相同的奇偶性(均为偶数或均为奇数),则新余数是 r 和 e 的和,否则它是 r 和 e (r-e) 之间的差。 ——最后剩下的就是比赛的结果。 示例:residu [1;3] 7 returns 5 作为以下计算的结果:

7 + 1 (same parity +) = 8
8 - 3 (parité différente -) = 5

这是我的代码,但它似乎不起作用:

let rec residue l n =
if l = [] then 0 else
if (((List.hd l) mod 2  <> 0) && (n mod 2 <> 0 )) || (((List.hd l) mod 2 == 0) && (n mod 2 ==  0 ))  
then  
(List.hd l)  + residue (List.tl l) ((List.hd l)+ n) else 
n - (List.hd l)  - residue (List.tl l) (n - (List.hd l));;
residu [1;3] 7;;
- : int = 6 (The correct result should be 5)

感谢您的帮助。

这是我的尝试。

let rec residue l n =
  let parity a b =
    if ((a mod 2 <> 0) && (b mod 2 <> 0)) ||
       ((a mod 2 == 0) && (b mod 2 == 0)) then true else false in
  match l, n with
    | [], n -> n
    | (x::xs), n -> if parity x n then residue xs (n+x) else residue xs (n-x)

希望对解决问题有所帮助。