Function 如何在Ocaml中打印函数返回值
如何在Ocaml中打印递归函数的整数类型返回值。我想查找数字的阶乘。我使用以下代码。但它显示了错误Function 如何在Ocaml中打印函数返回值,function,ocaml,Function,Ocaml,如何在Ocaml中打印递归函数的整数类型返回值。我想查找数字的阶乘。我使用以下代码。但它显示了错误 let rec factorial x = if (0 > x) then (raise Exit) else match x with | 0 -> 1 | n -> (n * (factorial (n - 1))) print_int (n * (factorial (n -
let rec factorial x =
if (0 > x) then (raise Exit)
else
match x with
| 0 -> 1
| n -> (n * (factorial (n - 1)))
print_int (n * (factorial (n - 1)));;
尝试运行时显示以下错误:
此表达式不是函数;无法应用它
错误的原因在于推断分支代码类型的方式。关于第一个分支的类型,类型检查器推断函数将生成一个int,但在函数体的末尾调用一个表达式,该表达式将生成一个单位类型
()
,因此无法正确推断函数的类型,然后以此类错误消息结束
为了避免这种情况,您需要通知编译器不应该考虑这个表达式,为了实现这一点,您可以使用函数ignore
,它作为类型注释'a->unit=
我稍微修改了代码的含义,为您提供了一个说明
let rec factorial = function
| n when n<0 -> raise (Failure "undefined: positive integer is required.")
| 0 -> 0
| 1 -> ignore (Printf.printf "1\n"); 1
| n -> ignore (Printf.printf "%d*" n); n * factorial (n-1)
;;
val factorial : int -> int = <fun>
我不确定我是否理解这个问题,也不知道祖尔的答案,所以这里是一个黑暗中的镜头。您忘记函数定义和“print_int”行之间的“;”了吗?从你的帖子上看不清楚,但如果你写道:
let rec factorial x =
if (0 > x) then (raise Exit) else
match x with
0 -> 1
| n -> (n * (factorial (n - 1)))
print_int (n * (factorial (n - 1)));;
那么它与:
let rec factorial x =
if (0 > x) then (raise Exit) else
match x with
0 -> 1
| n -> (n * (factorial (n - 1))) print_int (n * (factorial (n - 1)));;
所以你想要的是:
let rec factorial x =
if (0 > x) then (raise Exit) else
match x with
0 -> 1
| n -> (n * (factorial (n - 1)));;
print_int (n * (factorial (n - 1)));;
或者,没有“;”(有点过时):
当然,这还有另一个问题,当你调用print_int时,n是未绑定的,这就是为什么我不确定我是否理解了你的问题。但以下代码可以正常工作:
let rec factorial x =
if (0 > x) then (raise Exit) else
match x with
0 -> 1
| n -> (n * (factorial (n - 1)))
let () = print_int (factorial 10)
你能发布它显示的错误吗?错误是“这个表达式不是一个函数;它不能被应用”上面的代码对我有效。
let rec factorial x =
if (0 > x) then (raise Exit) else
match x with
0 -> 1
| n -> (n * (factorial (n - 1)))
let () = print_int (n * (factorial (n - 1)))
let rec factorial x =
if (0 > x) then (raise Exit) else
match x with
0 -> 1
| n -> (n * (factorial (n - 1)))
let () = print_int (factorial 10)