简体   繁体   English

OCaml中的递归帮助

[英]Recursion help in OCaml

I'm trying to make a recursive function with Ocaml, but I keep getting the same error code. 我正在尝试使用Ocaml进行递归函数处理,但是我不断收到相同的错误代码。

let rec get x =
if x > 7 then
get x-7;;

And I get the very useful error message of: 而且我得到了非常有用的错误消息:

Error: This expression has type int but an expression was expected of type unit 错误:此表达式的类型为int,但应为单位类型的表达式

I'm a complete beginner at OCaml, and studying it for a module at university. 我是OCaml的一个完整的初学者,正在大学里学习它作为一个模块。 And this is one of my assignments, and I'm a bit stuck! 这是我的任务之一,我有些困惑!

I originally wanted to do it by a while loop, (as I'm a predominantly imperative programmer), but I couldn't get that to work, so I thought I'd try recursive! 我本来想通过while循环来完成此操作(因为我是一个主要的命令程序员),但是我无法使其工作,所以我想尝试递归!

Thanks 谢谢

There's two problems with this code. 此代码有两个问题。 First, the spacing of x-7 indicates that you would like to pass x - 7 to get , but it will actually be parsed as (get x) - 7 . 首先, x-7的间距表示您希望传递x - 7get ,但实际上它会被解析为(get x) - 7 That's easily fixed with parentheses: 用括号很容易解决:

let rec get x =
  if x > 7 then get (x - 7)

The second problem is that you don't have a second arm for the if , so the function doesn't have much of a chance of returning anything. 第二个问题是if没有第二条臂,因此该函数返回任何东西的机会不大。 (One arm if is taken to be of type unit , only useful for effects.) if将手臂设为unit类型,则仅对效果有用。)

You probably want to return something if x is less than 7, maybe: 如果x小于7,您可能想返回一些值,也许是:

let rec get x =
  if x > 7 then get (x - 7) else x

Writing this with a while loop is possible, but you should understand that variables in OCaml are not mutable locations, only names. 可以使用while循环编写此代码,但是您应该了解OCaml中的变量不是可变的位置,而只是名称。 You'll have to introduce and manipulate mutable places explicitly: 您必须明确地引入和操作可变的位置:

let get x =
  let y = ref x in
  while !y > 7 do
    y := !y - 7;
  done;
  !y

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM