Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml type error

Tags:

types

int

ocaml

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

For practice, I'm trying to define a function "divides?" which inputs two ints and outputs a boolean describing whether 'int a' divides evenly into 'int b'. In my first attempt, I wrote something like this:

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

which gave the type error:

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

So then I tried to turn it around and I did this:

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

which didn't help much: 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;;

which elicited this: Characters 14-15: let divides? (a : int) (b : int) = ^ Error: This pattern matches values of type int but a pattern was expected which matches values of type 'a option.

I'm very confused and frustrated regarding the type system in general right now. (My first language was Scheme, this is my second.) Any help explaining where I'm going wrong and suggestions on how to fix it is much appreciated.

like image 955
Balthasar Avatar asked Dec 15 '22 22:12

Balthasar


1 Answers

The issue is that you can't use the question mark character ? in a variable/function name in OCaml. It's actually parsing your function declaration like this:

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

Note that the question mark is actually affecting the type of a, rather than being part of the name of the function.

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

Try removing the question mark from the name.

like image 53
Asherah Avatar answered Jan 08 '23 07:01

Asherah