Define a primitive data type: Difference between revisions

Content added Content deleted
m (Changed over to works with template)
(OCaml)
Line 233: Line 233:
}
}
}
}

=={{header|OCaml}}==
<ocaml>
exception Out_of_bounds

type 'a bounds = { min: 'a; max: 'a }

type 'a bounded = { value: 'a; bounds: 'a bounds }

let mk_bounds ~min ~max = { min=min; max=max } ;;
(** val mk_bounds : min:'a -> max:'a -> 'a bounds *)

let check_bounds ~value ~bounds =
if value < bounds.min || value > bounds.max then
raise Out_of_bounds ;;
(** val check_bounds : value:'a -> bounds:'a bounds -> unit *)

let mk_bounded ~value ~bounds =
check_bounds ~value ~bounds;
{ value=value; bounds=bounds } ;;
(** val mk_bounded : value:'a -> bounds:'a bounds -> 'a bounded *)

let op f a b =
let res = f a.value b.value in
if a.bounds <> b.bounds then
invalid_arg "different bounds";
check_bounds res a.bounds;
(mk_bounded res a.bounds)
;;
(** val op : ('a -> 'a -> 'a) -> 'a bounded -> 'a bounded -> 'a bounded *)
</ocaml>

Using in the interactive top level:
<ocaml>
# let range = mk_bounds 1 10 ;;
val range : int bounds = {min = 1; max = 10}

# let a = mk_bounded 2 range ;;
val a : int bounded = {value = 2; bounds = {min = 1; max = 10}}

# let b = mk_bounded 5 range ;;
val b : int bounded = {value = 5; bounds = {min = 1; max = 10}}

# let c = mk_bounded 14 range ;;
Exception: Out_of_bounds.

# op ( + ) a b ;;
- : int bounded = {value = 7; bounds = {min = 1; max = 10}}
</ocaml>

which can be used with floats in the same way:
<ocaml>
# let rf = mk_bounds 1.0 10.0 ;;
val rf : float bounds = {min = 1.; max = 10.}

# let a = mk_bounded 2.2 rf
and b = mk_bounded 5.4 rf ;;
val a : float bounded = {value = 2.2; bounds = {min = 1.; max = 10.}}
val b : float bounded = {value = 5.4; bounds = {min = 1.; max = 10.}}

# op ( +. ) a b ;;
- : float bounded =
{value = 7.6; bounds = {min = 1.; max = 10.}}
</ocaml>


=={{header|Perl}}==
=={{header|Perl}}==