Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ocaml

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?

like image 673
user2875126 Avatar asked Jan 13 '23 03:01

user2875126


1 Answers

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.

like image 135
Jeffrey Scofield Avatar answered May 24 '23 19:05

Jeffrey Scofield