Recursion Ocaml递归函数的使用
我必须编写一个递归函数来计算所有小于n的正整数之和 我的函数在顶层工作,但我无法在脚本中使用它:Recursion Ocaml递归函数的使用,recursion,ocaml,Recursion,Ocaml,我必须编写一个递归函数来计算所有小于n的正整数之和 我的函数在顶层工作,但我无法在脚本中使用它: let rec sum x= 如果x=0,则为0,否则x+和(x-1) 让()= Printf.Printf“%d\n”和4 我在编译时遇到以下错误: Error: This expression has type ('a -> 'b, out_channel, unit, unit, unit, 'a -> 'b) CamlinternalForm
let rec sum x=
如果x=0,则为0,否则x+和(x-1)
让()=
Printf.Printf“%d\n”和4
我在编译时遇到以下错误:
Error: This expression has type
('a -> 'b, out_channel, unit, unit, unit, 'a -> 'b)
CamlinternalFormatBasics.fmt
but an expression was expected of type
('a -> 'b, out_channel, unit, unit, unit, unit)
CamlinternalFormatBasics.fmt
Type 'a -> 'b is not compatible with type unit
最后一行。缺少一些括号。你想要这个:
let () =
Printf.printf "%d\n" (sum 4)
这在顶级也不会起作用
如果没有括号,则要求将
sum
(函数本身)作为参数传递给printf
什么是“脚本”?OCaml是一种编译语言。据我所知,它没有任何类似脚本的功能。无论如何,问题似乎是Printf.Printf“%d\n”sum 4
调用Printf
,其中有三个参数,最后两个参数是sum
和4
。要使用4
调用sum
,然后将结果传递给printf
,必须将其括起来。@glennsl确实如此,ocaml myscript.ml
表现为字节码编译,然后执行。绿洲广泛使用它。