gpt4 book ai didi

functional-programming - 如何查找 ML 字符串列表中出现的次数?

转载 作者:行者123 更新时间:2023-12-02 04:02:51 26 4
gpt4 key购买 nike

我是机器学习新手,这是我尝试编写一个接收函数:

  • 字符串列表 L
  • 字符串str
  • 整数计数器

该函数应返回 Lstr 出现的次数

这是我的代码:

(* 
* return number of occurences of str in L
* count should be initialized to zero.
*)
fun aux_num_of_occur(L: string list) (str:string) (count:int) =
if null L then 0
else if str = hd(L) then
aux_num_of_occur tl(L) str (count+1)
else
aux_num_of_occur tl(L) str count

这些是我得到的错误:

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

我的问题:

  1. 语法有什么问题?
  2. 我不清楚错误消息的内容:什么是在这种情况下,规则对象
  3. 如何通过递归调用函数返回int?是通过向其传递一个计数器作为参数吗?

最佳答案

这是一个经典错误:tl(L)tl L 是同一件事 - 在类似 ML 的语言中,您不需要括号来进行函数应用,您只需将函数和参数并置即可。

所以 aux_num_of_occurr tl(L) ...aux_num_of_occurr tl L ... 是一样的,即您正在尝试应用 aux_num_of_occurr code> 到 tl 函数,而不是字符串列表。现在,tl 函数的类型为 'a list -> 'a list,这就是您在错误消息中看到的内容(带有 'a那里是'Z)。

我应该说,这种带有 nullhdtl 函数的样式在 SML 中并不是很惯用 - 你可以使用模式数学代替。将 aux_num_of_occur 设为本地也更方便,可以防止命名空间污染,防止错误使用(您可以控制 count 的初始值)。此外,这还为您提供了在进一步递归时不必始终传递 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_of_occur 有一个更通用的类型 ''a list -> ''a -> int,其中 ''a 表示具有相等比较的任何类型。编译器会产生警告

Warning: calling polyEqual

您可以忽略它,也可以向num_of_occur添加一些类型注释。请参阅here了解更多详情。

关于functional-programming - 如何查找 ML 字符串列表中出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41073104/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com