Error like Ocaml

I am learning OCaml and this is my first typed language, so try to be patient with me:

For practice, I am trying to define the function of "shares?" which introduces two ints and outputs a boolean value that describes whether "int a" is evenly divided by "int b". In my first attempt, I wrote something like this:

let divides? ab = if a mod b = 0 then true else false;; 

which gave an error like:

 if a mod b = 0 then true ^ Error: This expression has type 'a option but an expression was expected of type int 

So, I tried to rotate it, and I did this:

 let divides? ab = match a mod b with 0 -> true |x -> false;; 

that didn't help: Characters 26-27 match a mod b with ^ Error: This expression has type 'a option but an expression was expected of type int

Then I tried this:

 let divides? (a : int) (b : int) = match a mod b with 0 -> true |x -> false;; 

who caused this: Characters 14-15: let him share? (a: int) (b: int) = ^ Error: this pattern matches values โ€‹โ€‹of type int but a pattern that matches values โ€‹โ€‹of type "variant" was expected.

I am very confused and disappointed with the type system as a whole right now. (My first language was Scheme, this is my second.) Any help explaining where I am going wrong and suggestions on how to fix it are greatly appreciated.

+4
source share
1 answer

The problem is that you cannot use the question mark ? in the variable / function name in OCaml. It actually parses the declaration of your function as follows:

 let divides ?ab = if a mod b = 0 then true else false 

Note that the question mark actually affects type a , and is not part of the function name.

This means that a is an optional parameter , so it is assigned the type 'a option for some 'a .

Try removing the question mark from the name.

+12
source

All Articles