I have a bug in my program in OCaml and I am looking for help.
the error:
This expression has type unit but an expression was expected of type int
The line error with the error contains soma = soma
let soma = 0;;
let rec nBell n =
if n == 0 then 1
else
for k=0 to n-1 do
soma = soma + ((fact(n-1)/(fact(k)*fact((n-1)-k))) * nBell(k));
done;;`
Can anyone help me?
As has recently been mentioned here quite a few times, OCaml has no statements. It only has expressions. For an if
expression to make sense, the then
and else
parts have to be the same type. In your code the then
part is 1
. I.e., it has type int
. In the else
part you have a for
expression. The type of a for
expression is unit
. So that's what the compiler is complaining about.
However, fixing this problem will be just the first step, as your code is based on a misunderstanding of how OCaml variables work. OCaml variables like soma
are immutable. You can't change their value. So the expression soma = soma + 1
is actually a comparison that tells whether the two values are equal:
# let soma = 0;;
val soma : int = 0
# soma = soma + 1;;
- : bool = false
Generally speaking, you need to find a way to solve your problem without assigning to variables; i.e., without changing their values.
If you're just starting with functional programming, this seems absurd. However it turns out just to be another way to look at things.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With