英文:
Function to Return Datatypes in SML
问题
为了家庭作业,我需要设计一个SML函数,该函数返回与某些输入数据匹配的自定义数据类型的类型。
这里是一般的想法:我们有一个自定义数据类型typ--
datatype typ = typ1
|typ2
|typ3
.
.
.
|typn
我们要编写的函数具有以下类型:
(foo -> typ option)
由于该函数不返回字符串,而是返回typ option,我理解这个函数在最基本的层次上需要看起来像这样--
hw_fun x =
case x of
p1 => SOME typ1
|p2 => SOME typ2
.
.
.
|pn => SOME typn
|_ => NONE
--假设p1匹配typ1,依此类推。我的问题是,如何使数据类型成为匹配情况的返回值?
希望这有意义,提前感谢您的帮助!
英文:
For homework, I need to design an SML function that returns the type of a custom datatype which matches some input data.
Here's the general idea: we are given a custom datatype typ--
datatype typ = typ1
|typ2
|typ3
.
.
.
|typn
The function we're supposed to write has this type:
(foo -> typ option)
Since the function isn't returning a string but instead typ option, I understand the function, on the most basic level, as needing to look something like this --
hw_fun x =
case x of
p1 => SOME typ1
|p2 => SOME typ2
.
.
.
|pn => SOME typn
|_ => NONE
--assuming p1 matches typ1, etc. My question is, how do I make a datatype the return value of a matching case?
Hope that makes sense, thanks in advance for the help!
答案1
得分: 0
Type inferencing will take care of you. Consider the following.
datatype foo = Bar | Baz;
fun wooble n =
case n of
1 => SOME Bar
| 2 => SOME Baz
| _ => NONE;
The wooble
function is inferred to have type int → foo option
. If I wished to use explicit type notations, I might write:
fun wooble (n : int) : foo option =
case n of
1 => SOME Bar
| 2 => SOME Baz
| _ => NONE;
Of course, in this case, the case
expression is extraneous.
fun wooble 1 = SOME Bar
| wooble 2 = SOME Baz
| wooble _ = NONE
You only get in trouble with type inferencing if you try to return something of a different type from your function. E.g.
fun wooble 1 = SOME Bar
| wooble 2 = SOME Baz
| wooble _ = "NONE";
英文:
Type inferencing will take care of you. Consider the following.
datatype foo = Bar | Baz;
fun wooble n =
case n of
1 => SOME Bar
| 2 => SOME Baz
| _ => NONE;
The wooble
function is inferred to have type int → foo option
. If I wished to use explicit type nnotations, I might write:
fun wooble (n : int) : foo option =
case n of
1 => SOME Bar
| 2 => SOME Baz
| _ => NONE;
Of course, in this case the case
expression is extraneous.
fun wooble 1 = SOME Bar
| wooble 2 = SOME Baz
| wooble _ = NONE
You only get in trouble with type inferencing if you try to return something of a different type from your function. E.g.
fun wooble 1 = SOME Bar
| wooble 2 = SOME Baz
| wooble _ = "NONE"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论