2009-07-07 72 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