tags:

views:

128

answers:

2

Hi

Im trying to make a function that will return an element of type "point":

type point = {x : int, y : int};
fun pointadd (p1: point, p2: point) = (((#x p1) + (#x p2)), ((#y p1) + (#y p2)));

but SMLNJ doesn't seem to understand my intention that the result should be of type "point" as well:

use "test1.sml";
[opening test1.sml]
type point = {x:int, y:int}
val pointadd = fn : point * point -> int * int
A: 

It's been quite a while since my SML days but afair the type system does not resolve defined types automatically when printing the type signature. You could try something like this:

fun pointadd (p1: point, p2: point) = (((#x p1) + (#x p2)), ((#y p1) + (#y p2))): point
RobertB
that returns a syntax error:- use "test1.sml";[opening test1.sml]type point = {x:int, y:int}test1.sml:3.39-3.88 Error: expression doesn't match constraint [tycon mismatch] expression: int * int constraint: point in expression: ((fn <pat> => <exp>) p1 + (fn <pat> => <exp>) p2, (fn <pat> => <exp>) p1 + (fn <pat> => <exp>) p2): pointuncaught exception Error raised at: ../compiler/TopLevel/interact/evalloop.sml:66.19-66.27 ../compiler/TopLevel/interact/evalloop.sml:44.55 ../compiler/TopLevel/interact/evalloop.sml:296.17-296.20
loldrup
+2  A: 

point is a record type, but you are returning a tuple instead.

How about something like this:

fun pointadd (p1: point, p2: point) =
    { x = #x p1 + #x p2,
      y = #y p1 + #y p2 };

You can add a type guard on the return type to make the type nicer, but it's equivalent:

fun pointadd (p1: point, p2: point) : point =
    { x = #x p1 + #x p2,
      y = #y p1 + #y p2 };
newacct
Spot on! Problem solved :)
loldrup
@loldrup: If the problem is solved, you should **Accept** this answer, by clicking the green check mark underneath the vote counter.
ephemient