nuk
nuk

Reputation: 329

In OCaml, how to predicate a variable is a List?

For example,

let x = ["a";"b";"c";"d"];;

let listp = if (x.isa(List)) then true else false;;

Is there something like a "isa" method in OCaml to predicate a variable is a List/Array/Tuple... and so on?

Upvotes: 1

Views: 2980

Answers (3)

Rowenia
Rowenia

Reputation: 51

Not really: everything has a type associated with it, so either it's already known that it's a list, or it's polymorphic (like 'a), in which case we're not "allowed" to know about the underlying type. Doing anything type-specific in that case would force specialization of the value's type.

Upvotes: 0

Pacane
Pacane

Reputation: 21471

Can't you just match x with something specific to your type? For example, for a sequence:

let listp = match x with | h::t -> true | _ -> false

for a tuple, I don't remember the exact syntax, but something like match x with | (k,v) -> true

and so on...

Upvotes: 1

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

OCaml has no constructs for testing the type of something. A good rule of thumb is that types are either fixed or are completely unknown. In the first case, there's no need to test. In the second case, the code is required to work for all possible types.

This works out a lot better than you might expect if you're used to other languages. It's kind of a nice application of the zero/one/infinity rule.

Note that there is no trouble defining a type that contains one of a set of types you are interested in:

type number = MyFloat of float | MyInt of int

Values of this type look like: MyFloat 3.1 or MyInt 30281. You can, in effect, test the type by matching against the constructor:

let is_int x = match x with MyFloat _ -> false | MyInt _ -> true

The same is true for lists and arrays, except that these are parameterized types:

type 'a collection = MyArray of 'a array | MyList of 'a list


let is_list x = match x with MyArray _ -> false | MyList _ -> true

What you get back for the lack of so-called introspection is that you can easily construct and deconstruct values with rich and expressive types, and you can be assured that functions you call can't mess with a value when they don't know what its type is.

Upvotes: 4

Related Questions