You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OCaml递归生成卡特兰数时Int64类型不兼容报错,如何解决?

OCaml中使用Int64类型生成卡特兰数的修复方案

你的代码报错的核心原因是:OCaml的原生算术运算符(+、-、*、/)仅支持int类型,直接用这些运算符操作int64值会触发类型不匹配;同时循环变量i是int类型,无法直接传给期望int64参数的函数。

以下是修复后的完整代码,确保全程使用int64类型运算:

let rec f (n : int64) =
  if Int64.compare n 1L < 0 then 1L
  else
    let term = Int64.sub (Int64.mul 4L n) 2L in
    let numerator = Int64.mul term (f (Int64.sub n 1L)) in
    Int64.div numerator (Int64.add n 1L)
;;

for i = 0 to 50 do
  Printf.printf "%Ld\n" (f (Int64.of_int i))
done;

关键修改说明:

  • 比较操作:用Int64.compare替代原生<运算符,专门用于int64类型的数值比较
  • 算术运算:所有加减乘除操作替换为Int64模块的专用函数:
    • Int64.mul:int64乘法
    • Int64.sub:int64减法
    • Int64.add:int64加法
    • Int64.div:int64除法
  • 类型转换:循环中用Int64.of_int i将int类型的循环变量转换为int64,匹配函数参数类型
  • 格式输出:用%Ld格式符打印int64类型的值,替代原代码中用于int的%d

内容的提问来源于stack exchange,提问作者DialFrost

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 01:01:22