yair
yair

Reputation: 95

OCaml union types

I'm trying to make a function that uses a subtype of a defined type but OCaml wont derive the correct value : Consider this type definition:

type fraction = {numerator : int; denominator : int};;

type number =
  | Int of int
  | Fraction of fraction;;

if i try to type into the interpeter (i'm using utop if it matters) :

utop # ((fun a-> a>0) (Int 1));;
Error: This expression has type number but an expression was expected of type int 

type number is also an int but I cant get the function to understand that, how can I solve this?

Upvotes: 4

Views: 3389

Answers (2)

Marth
Marth

Reputation: 24802

You can use pattern matching in the fun:

# (fun (Int a) -> a > 0) (Int 1);;
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
Fraction _
- : bool = true

Obviously this will raise a match error if you pass in a Fraction. If you want to handle that case:

# (function Int a -> a > 0 | Fraction {numerator = a; denominator = b}  -> a/b > 0 ) (Int 1);;
- : bool = true

Upvotes: 2

gsg
gsg

Reputation: 9377

The 0 in a>0 is an int, so that is the type the function expects as an argument. What you probably want is for the 0 to be the equivalent number, like this:

# (fun a -> a > Int 0) (Int 1)
- : bool = true

Upvotes: 2

Related Questions