Joe
Joe

Reputation: 61

How to construct a correct type transformation in OCaml?

In order to map from a constructed type tainted_value to other types, and from other basic types to the constructed type tainted_value, there are two functions constructed.

First, the type tainted_value is defined as:

type object_ = int 
and location = Obj of object_ | Null
and closure = var * cmd * stack
and value = Fld of string | Int of int | Loc of location | Clo of closure
and tainted_value = Val of value | Error

If I just let my first function mapping from tainted_value to string look like:

let tva_to_string tva1 = match tva1 with 
  | Val (Fld e) -> e 
  | _ -> None

It reports error as:

This expression has type 'a option but an expression was expected of type string

However, it will not return error if I change None into failwith "Empty":

let tva_to_string tva1 = match tva1 with
  | Val (Fld e) -> e 
  | _ -> failwith "Empty"

Why?

Upvotes: 0

Views: 165

Answers (1)

Chris
Chris

Reputation: 36451

None is a constructor for the option type. If one clause in a match returns None then the others must return some other value of type option. They may also raise an exception, which is what the failwith function does.

The other constructor for option is Some, so you may be looking for:

let tva_to_string tva1 = match tva1 with 
  | Val (Fld e) -> Some e 
  | _ -> None

This will alleviate your type-checking issues. Of course, it still doesn't return a string so your naming of the function either needs some work, or you need to return strings.

Upvotes: 2

Related Questions