Lavair
Lavair

Reputation: 946

How do I change type variables in OCaml?

Assuming we've got the following type and type variable:

type example_type = A | B | C of example_type * example_type * example_type
let ab = C(A, C(A, B))

How can I manage to output a modification or a modified copy of ab?
For example the following should be fulfilled:
val ab : example_type = C(A, C(A, A)) or val new_ab : example_type = C(A, C(A, A))

Upvotes: 0

Views: 1166

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

Values of the type example_type are immutable. And variables in OCaml (like ab) are also immutable. So you can't change the value that ab is bound to, or change the internals of the value itself.

In functional programming, you calculate new values rather than modifying old ones.

For what it's worth, your example value isn't valid for your example_type as declared. The C constructor takes 3 values, but you have only 2.

Also, ab is just a variable, not a type variable. It's a name bound to a value of type example_type.

Here is a function that eliminates all the Bs from a value of type example_type. It replaces them with A instead.

let rec replace_b x =
    match x with
    | B -> A
    | A -> A
    | C (p, q, r) ->
        C (replace_b p, replace_b q, replace_b r)

Note that this function doesn't modify its parameter x. It constructs a new value.

Upvotes: 2

Related Questions