user2875126
user2875126

Reputation: 51

This expression has type unit but an expression was expected of type int

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?

Upvotes: 5

Views: 17213

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

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.

Upvotes: 10

Related Questions