Reputation: 296
Is it possible to define a list using variants (or something else) which would contain integers and functions simultaneously? I am particularly interested in mixing functions and some other type in a list.
Analogously is it possible to create a function which could return either a number or a function? Please if possible give code examples of both cases.
Upvotes: 0
Views: 517
Reputation: 35210
Of course, both is possible in OCaml.
If you want to make it possible for an expression, to evaluate to a value of two (or more different types), then it means, that you want to create a new type that will include all these types. Recall, that a type can be compared with a set. So, if you want to define a new type t
, that can contain values of type t1
and t2
, then you need to have a union. Since types t1
and t2
have different properties, it is natural, that we would like to have an ability to distinguish them later, so we would like to make the union discriminated. It happens, that OCaml has a built-in support for discriminated unions - variants, e.g.,
type t = T1 of t1 | T2 of t2
This type definition creates a new type, that is a discriminated union of types t1
and t2
. The definition naturally creates projection and injection function. To inject a value x
of type t1
into type t
, use T1 x
(correspondingly for a value x
of type t2
, use T2 x
). Use pattern match to project a value y
from type t
to either t1
or t2
, e.g., match y with T1 -> ... | T2 -> ...
.
Upvotes: 1
Reputation: 1619
type my_elt =
| Null
| Int of int
| Fun1 of (int-> unit)
| Fun2 of (int-> int)
let eval a =function
| Fun1 f -> f a;Null
| Fun2 f -> Int (f a)
| _ -> Null
let leval a l = List.map (fun elt -> eval a elt ) l
;;
Test :
let l=[Int 2;Fun1 (Printf.printf "%d");Fun2 ((+)2) ]
# leval 2 l;;
2- : my_elt list = [Null; Null; Int 4]
Upvotes: 2