Version française
Home     About     Download     Resources     Contact us    
Browse thread
ambitious proposal: polymorphic arithmetics
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Richard Jones <rich@a...>
Subject: Re: [Caml-list] ambitious proposal: polymorphic arithmetics
On Wed, Apr 06, 2005 at 08:01:00PM +0200, padiolea@irisa.fr wrote:
> In the module Obj of the caml library there is a function
>  external is_int : t -> bool = "%obj_is_int"
> I guess that the value are represented internally as "cells" and that
> cells have a bit indicating wether it is an int or a pointer (and also
> a bit for the gc)

Internally as "values".  The LSB indicates whether a value is an int
or a pointer to something boxed.  (LSB = 1 => int).  For boxed data
the header tells you what it is and how big it is.

> By using more bits we could know wether or not it is a float, and
> so have also a function
>  is_float: t -> bool
> and so we could then code a "generic" + function

Floats are normally stored boxed, except when they happen to be in
registers, or they are stored in an array.

Anyway, it's already possible to write some generic functions,
provided you confine yourself to the type information available at
runtime.  For example, a slow generic (+) is:

  open Printf
  
  type t = Int of int | Float of float
  
  let (+) a b =
    let get_type v =
      let r = Obj.repr v in
      if Obj.is_int r then
        Int (Obj.magic r : int)
      else if Obj.size r = 2 && Obj.tag r = Obj.double_tag then
        Float (Obj.magic r : float)
      else (
        prerr_endline ("size = " ^ string_of_int (Obj.size r) ^ ", tag = " ^
  		       string_of_int (Obj.tag r));
        invalid_arg "(+): arguments must have type int or float"
      )
    in
    match get_type a, get_type b with
      | Int a, Int b -> Int (a + b)
      | Float a, Float b -> Float (a +. b)
      | Int a, Float b -> Float (float a +. b)
      | Float a, Int b -> Float (a +. float b)
  
  let string_of_t = function
    | Int a -> string_of_int a
    | Float a -> string_of_float a
  
  let () =
    print_endline (string_of_t (1 + 2));
    print_endline (string_of_t (1. + 2));
    print_endline (string_of_t (1 + 2.));
    print_endline (string_of_t (1. + 2.))

See also the function 'dump' in:

http://cvs.sourceforge.net/viewcvs.py/ocaml-lib/extlib-dev/std.ml?rev=1.15&view=markup

> My big wish for ocaml would be to have some better tracing facilities,
> a generic print function, and the possibilty to print backtraces,

Being able to print full backtraces (with function names and
parameters) would be just great.

Rich.

-- 
Richard Jones, CTO Merjis Ltd.
Merjis - web marketing and technology - http://merjis.com
Team Notepad - intranets and extranets for business - http://team-notepad.com