Sml 数据类型Nt=int |字符串,单位为ML
当我只有Sml 数据类型Nt=int |字符串,单位为ML,sml,ml,Sml,Ml,当我只有数据类型Nt=int | string时,sml不会抱怨。但是当我还有valn=6:Nt时,ml不接受6作为Nt。为什么会这样?我确实知道,通常在int和string之前应该有数据构造函数,但这里我要定义的函数可以是int或string 您误解了代码。需要明确的是,您不能在没有构造函数的情况下定义数据类型。但是ML有不同的类型和值的名称空间。示例中出现的int和string是值标识符。因此,它们只定义了新的空构造函数,对于相同名称的类型,它们的作用绝对为零。现在可以定义val n=int
数据类型Nt=int | string
时,sml不会抱怨。但是当我还有valn=6:Nt
时,ml不接受6作为Nt
。为什么会这样?我确实知道,通常在int
和string
之前应该有数据构造函数,但这里我要定义的函数可以是int
或string
您误解了代码。需要明确的是,您不能在没有构造函数的情况下定义数据类型。但是ML有不同的类型和值的名称空间。示例中出现的int
和string
是值标识符。因此,它们只定义了新的空构造函数,对于相同名称的类型,它们的作用绝对为零。现在可以定义val n=int:Nt
。这就好像您编写了datatypent=foo | bar
一样,该函数可以接受int或字符串,可以用两种方式进行解释。你可以说你想要一个函数,它可以接受任何东西,并用它做一些一般性的事情——这将是一个多态函数。例如
fun id x = x
可以同时获取int和string并返回它们,但不能在特定的环境中处理它们的内容。如果您想要一个可以接受int或string的函数,并根据您拥有的输入对其执行不同的操作,则可以使用联合类型,例如
这里,Int
和Str
是值构造函数,它们的工作方式类似于函数,它们分别将Int/string类型的值作为参数,并返回联合类型Nt的值。我将它们命名为int
和string
以外的名称,以表示值构造函数不同于int和string类型。如果他们不接受一个论点,他们唯一的用途就是区分一个论点和另一个论点(在这种情况下,他们将同构于true
/false
)
将此类值作为输入的函数必须与同名的模式构造函数匹配。以下是一些将此联合类型作为参数的函数:
fun isAnInt (Int i) = true
| isAnInt (Str s) = false
fun intVal (Int i) = i
| intVal (Str i) = 0
fun strVal (Int i) = Int.toString i
| strVal (Str s) = s
fun sumNt [] = 0
| sumNt (x::xs) = intVal x + sumNt xs
fun concatNt [] = ""
| concatNt (x::xs) = strVal x ^ concatNt xs
这些功能正在测试中:
val test_isAnInt_1 = isAnInt sample_1 = true
val test_isAnInt_2 = isAnInt sample_2 = false
val test_intVal_1 = intVal sample_1 = 42
val test_intVal_2 = intVal sample_2 = 0
val test_strVal_1 = strVal sample_1 = "42"
val test_strVal_2 = strVal sample_2 = "Hello"
val test_sumNt_1 = sumNt [] = 0
val test_sumNt_2 = sumNt [sample_1, sample_1, sample_2, sample_1] = 126
val test_sumNt_3 = sumNt [sample_2, sample_2, sample_2] = 0
val test_concatNt_1 = concatNt [] = ""
val test_concatNt_2 = concatNt [sample_1, sample_1, sample_1] = "424242"
val test_concatNt_3 = concatNt [sample_1, sample_2, sample_1] = "42Hello42"
val test_isAnInt_1 = isAnInt sample_1 = true
val test_isAnInt_2 = isAnInt sample_2 = false
val test_intVal_1 = intVal sample_1 = 42
val test_intVal_2 = intVal sample_2 = 0
val test_strVal_1 = strVal sample_1 = "42"
val test_strVal_2 = strVal sample_2 = "Hello"
val test_sumNt_1 = sumNt [] = 0
val test_sumNt_2 = sumNt [sample_1, sample_1, sample_2, sample_1] = 126
val test_sumNt_3 = sumNt [sample_2, sample_2, sample_2] = 0
val test_concatNt_1 = concatNt [] = ""
val test_concatNt_2 = concatNt [sample_1, sample_1, sample_1] = "424242"
val test_concatNt_3 = concatNt [sample_1, sample_2, sample_1] = "42Hello42"