SML/NJ模式匹配的一个动态的打字
-
05-07-2019 - |
题
是否有可能编写的功能与动态类型的输入参数?我试着模式匹配,但显然它不能这样工作。
我想要做这样的事情:
fun firstStr (0,n:string) = n
| firstStr (b:string,n:string) = if b>n then n else b;
谢谢你。
解决方案
StandardML是严格的,静态型的语言。因此,不可能有一个功能接受一个int在第一种情况下,一串在第二位。误差你得到的是
this clause: string * string -> 'Z
previous clauses: int * string -> 'Z
in declaration:
firstStr =
(fn (0,<pat> : string) => n
| (<pat> : string,<pat> : string) => if <exp> > <exp> then n else b)
如果你想要有一种情况下,这是一个串和一种情况下,这是一个int,你可以做一个新的类型,"带标记的联盟"(又名"歧视联盟"),其设计是易于使用模式匹配。它看起来是这样的:
datatype Wrapper = Int of int
| String of string
fun firstStr(Int 0, n:string) = n
| firstStr(String b, n:string) = if b>n then n else b
当然,你可能想找到一些更多的适当名称为这个包装类型,一些有意义的背景下你的方案。还请注意,在类型上注释 n
是不是真的有必要的;这将是更习惯用语来写
fun firstStr(Int 0, n) = n
| firstStr(String b, n) = if b>n then n else b
此外,编译器会告诉你你已经离开的情况下发现的:如果第一个参数是一个整数不等于零?
最后,这是不真的清楚你是什么意思的比较 b>n
, 什么方面的两个字符串没有你想来比较?我看到那时的我比较两个字符串中SML,我看到一个字典式(又名字母)的比较。这就是你想要的吗?
其他提示
稍微说一下,假设你有两个参数,每个参数可以是一个字符串或一个整数,如果你有两个字符串你想要字典缩小字符串,如果你有一个字符串你想要那个字符串,并且如果你有两个整数,你不能返回一个字符串。你是做什么?返回 string option
类型的值(在选项, SOME
和 NONE
http://www.standardml.org/Basis/option.html"rel =“noreferrer”> http://www.standardml.org/Basis/option.html :
datatype string_or_int = String of string
| Int of int
fun firstStr(String a, String b) = SOME (if a < b then a else b)
| firstStr(String a, Int _ ) = SOME a
| firstStr(Int _, String b) = SOME b
| firstStr(Int _, Int _ ) = NONE
函数 firstStr
的类型为
string_or_int * string_or_int -> string option
成为精通ML程序员的最快方法是学会先考虑类型。例如,您真正想要的是类型 string option * string - &gt;的函数。字符串
,你不需要自己写;内置函数 getOpt
就是这样做的。另一方面,听起来你想要 string option * string - &gt;字符串
,所以你可以写
fun firstStr(SOME a, b) = if a < b then a else b
| firstStr(NONE, b) = b
并且您不需要在结果上使用 SOME
值构造函数或选项
类型。