List Info

Thread: Re: Re: Re: "ocaml_beginners"::[] Am I overtyping?




Re: Re: Re: "ocaml_beginners"::[] Am I overtyping?
country flaguser name
United States
2007-10-12 10:52:00

From: olsongt%40verizon.net">olsongtverizon.net
> I thought I liked this approach, but check out the last function in
> the following code. That's as bad as a C typedef.

Nevermind, got it. This is exactly what I want. I'm a little
suprised the first annotation says "vector" instead of "'a" but it
works the way I want. Thanks.

# let plus_one (v_or_p:'a) : 'a =
{x=v_or_p.x +. 1.;y=v_or_p.y +. 1.;z=v_or_p.z +. 1.};;
val plus_one : vector -> vector = <fun>;
# plus_one (make_point 1. 2. 3.);;
- : point = {x = 2.; y = 2.; z = 2.}
# plus_one {x=1.;y=2.;z=3.};;
- : vector = {x = 2.; y = 3.; z = 4.}
#

__._,_.___
.

__,_._,___
Re: Re: Re: "ocaml_beginners"::[] Am I overtyping?
country flaguser name
United States
2007-10-12 11:32:53

On Fri, 12 Oct 2007 10:52:00 -0500 (CDT), olsongt wrote

> Nevermind, got it. This is exactly what I want. I'm a little
&gt; suprised the first annotation says "vector" instead of "'a&quot; but it
> works the way I want. Thanks.

Well, that's because it can't be an 'a. The code makes use of record fields
x, y, and z, and not all types have those. In fact, just the currently
defined type vector = { x : float; y : float; z : float; } has it. Thus,
the type checker unifies 'a with vector.

> # let plus_one (v_or_p:'a) : 'a =
> {x=v_or_p.x +. 1.;y=v_or_p.y +. 1.;z=v_or_p.z +. 1.};;
&gt; val plus_one : vector -> vector = <fun>;
> # plus_one (make_point 1. 2. 3.);;
&gt; - : point = {x = 2.; y = 2.; z = 2.}
> # plus_one {x=1.;y=2.;z=3.};;
> - : vector = {x = 2.; y = 3.; z = 4.}

Of course this is still behaving in the exact same way, it's just that here
we get a bit of extra type naming information passed into the type
inferencer so that it can report back the name point in stead of the
equivalent vector or { x : float; y : float; z : float; }. They're still
the same thing and can be interchanged willy nilly:

# let f (p : point) = p.x +. p.y +. p.z;;
val f : point -> float = <fun>;
# let v = { x = 1.; y = 2.; z = 3. };;
val v : vector = {x = 1.; y = 2.; z = 3.}
# f v;;
- : float = 6.

Or:

# let plus_one (v_or_p:point) : vector =
{x=v_or_p.x +. 1.;y=v_or_p.y +. 1.;z=v_or_p.z +. 1.};;
val plus_one : point -> vector = <fun>;
# plus_one v;;
- : vector = {x = 2.; y = 3.; z = 4.}
# plus_one (make_point 1. 2. 3.);;
- : vector = {x = 2.; y = 2.; z = 2.}

--

William D. Neumann

__._,_.___
.

__,_._,___
[1-2]

about | contact  Other archives ( Real Estate discussion Medical topics )