确保 SML 中的特定类型结果

发布于 2024-07-26 02:03:14 字数 422 浏览 2 评论 0原文

我试图创建一个返回“point”类型元素的函数:

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

但是 SMLNJ 似乎没有为了理解我的意图,结果也应该是“point”类型:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蝶舞 2024-08-02 02:03:14

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 };

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 };
记忆里有你的影子 2024-08-02 02:03:14

自从我使用 SML 以来已经有一段时间了,但是类型系统在打印类型签名时不会自动解析定义的类型。 你可以尝试这样的事情:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文