Reputation: 54
I'm trying to make a recursive function with Ocaml, but I keep getting the same error code.
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
I'm a complete beginner at OCaml, and studying it for a module at university. 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!
Thanks
Upvotes: 0
Views: 133
Reputation: 9377
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
. 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. (One arm if
is taken to be of type unit
, only useful for effects.)
You probably want to return something if x
is less than 7, maybe:
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. 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.
Upvotes: 7