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!
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"