2009-07-07 43 views
0

我试着做出会返回一个类型的“点”元素的功能:确保SML特定类型的结果

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

SMLNJ似乎并不理解我的意图,其结果应该是类型“点”,以及:

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

回答

2

point是一个记录类型,但你是不是返回一个元组。

怎么是这样的:

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

您可以在返回类型添加型后卫做出型更好,但它是等价的:

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

现货!问题解决了:) – loldrup 2009-07-07 07:48:51

0

它已经相当一段时间,因为我的SML天,但AFAIR类型系统不能自动解决定义类型的打印类型签名时。你可以尝试这样的事:

fun pointadd (p1: point, p2: point) = (((#x p1) + (#x p2)), ((#y p1) + (#y p2))): point 
+0

返回一个语法错误: - 使用“test1.sml”; [开放test1.sml] 类型点= {x:int,y:int} test1.sml:3.39-3.88错误:表达式不匹配约束[tycon不匹配] 表达式:int * int 约束:point 在表达式: ((FN =>)P1 +(FN =>)P2, (FN =>)P1 +(FN =>)P2):点 未捕获的异常的错误 提出:../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 2009-07-07 07:38:14