Functional programming 如何在ML字符串列表中查找出现次数?
我是ML新手,以下是我编写函数的尝试,该函数接收:Functional programming 如何在ML字符串列表中查找出现次数?,functional-programming,sml,smlnj,ml,Functional Programming,Sml,Smlnj,Ml,我是ML新手,以下是我编写函数的尝试,该函数接收: 字符串列表 字符串str 整数计数器 函数应返回L中出现的str的次数 这是我的密码: 这些是我得到的错误: Error: case object and rules don't agree [tycon mismatch] rule domain: string list * string * int object: ('Z list -> 'Z list) * 'Y * 'X in expression: (c
- 字符串列表
- 字符串str
- 整数计数器
L
中出现的str
的次数
这是我的密码:
这些是我得到的错误:
Error: case object and rules don't agree [tycon mismatch]
rule domain: string list * string * int
object: ('Z list -> 'Z list) * 'Y * 'X
in expression:
(case (arg,arg,arg)
of (L : string list,str : string,count : int) =>
if null L
then 0
else if <exp> = <exp> then <exp> <exp> else <exp> <exp>)
uncaught exception Error
raised at: ../compiler/TopLevel/interact/evalloop.sml:66.19-66.27
../compiler/TopLevel/interact/evalloop.sml:44.55
../compiler/TopLevel/interact/evalloop.sml:296.17-296.20
错误:案例对象和规则不一致[tycon不匹配]
规则域:字符串列表*string*int
对象:('Z list->'Z list)*'Y*'X
在表达上:
(案例(arg,arg,arg)
of(L:string列表,str:string,count:int)=>
如果为空L
然后0
else if=然后else)
未捕获异常错误
在以下位置引发:../compiler/TopLevel/interact/evalloop.sml:66.19-66.27
../compiler/TopLevel/interact/evalloop.sml:44.55
../compiler/TopLevel/interact/evalloop.sml:296.17-296.20
我的问题:
规则
和本例中的对象
int
?是否将计数器作为参数传递给它李>
这是一个典型的错误:tl(L)
和tl
是同一件事——在类似ML的语言中,函数应用不需要括号,只需将函数和参数并置即可
因此,aux\u num\u of theu occure tl(L)…
与aux\u num\u of theu occure tl…
是一样的,也就是说,您试图将aux\u num\u of theu occure
应用于tl
函数,而不是字符串列表。现在,tl
函数的类型为'a list->'a list
,这就是您在错误消息中看到的(其中'a
为'Z
)
我应该说,这种样式与那些null
、hd
和tl
函数在SML中不是很惯用——您可以使用模式匹配。还可以更方便地将出现的辅助数量设置为本地,以防止名称空间污染,防止不正确的使用(您可以控制计数的初始值)。此外,这使您在进一步递归时不必一直传递str
fun num_of_occur ss str =
let
fun loop [] count = count
| loop (s::ss) count =
if s = str
then loop ss (count + 1)
else loop ss count
in
loop ss 0
end
请注意,num\u of_occurrent
有一个更一般的类型'a list->'a->int
,其中'a
表示具有相等比较的任何类型。编译器将生成一个警告
警告:呼叫Polyqual
您可以忽略它,也可以将一些类型注释添加到num\u of\u occurrent
。更多细节请参见。另外,下面是折叠的样子:fun num\u of_发生ss str=foldl(fn(s,count)=>如果s=str,那么count+1 else count)0 ss
@SimonShine或者,如果我想想象一下(并且为了说明如果
是一个表达式):fun num\u of_发生ss str=foldl(fn(s,count)=>count+(如果s=str,那么1其他0)0 ss
@SimonShine我认为这是属于它自己的答案!查找此问题的人应该能够看到简洁、惯用的高阶解决方案以及显式递归解决方案(但是,为了清楚起见,请命名您的帮助函数!):)。
fun num_of_occur ss str =
let
fun loop [] count = count
| loop (s::ss) count =
if s = str
then loop ss (count + 1)
else loop ss count
in
loop ss 0
end