我遇到了一个Ocaml函数的问题,该函数接受两个输入,并且应该给出一个特定的输出
我正在做一个家庭作业,通常,我知道为什么会发生错误,然而,对于这两个问题,我不知道发生了什么。我不确定是模式匹配还是模式匹配后我试图解决的问题我遇到了一个Ocaml函数的问题,该函数接受两个输入,并且应该给出一个特定的输出,ocaml,Ocaml,我正在做一个家庭作业,通常,我知道为什么会发生错误,然而,对于这两个问题,我不知道发生了什么。我不确定是模式匹配还是模式匹配后我试图解决的问题 Given a STRING LIST and INT return a STRING LIST that contains all the strings with a length greater than the given int let rec long_strings (l: string list) (i: int) : str
Given a STRING LIST and INT return a STRING LIST
that contains all the strings with a length greater than the given int
let rec long_strings (l: string list) (i: int) : string list =
match l with
| [] -> []
| head :: tail -> if (String.length head > i)
then head :: (long_strings tail)
else (long_strings tail)
错误
另一个类似的问题
(*Given an INT LIST and INT divide the numbers in the given int
list by the given int and return an (INT * INT) LIST containing
the dividend and the remainder*)
let rec remainders (l: int list) (i: int) : (int * int) list =
match l with
| [] -> []
| head :: tail -> ((head / i), (head mod num)) :: (remainders tail)
;;
错误
你错过了一场辩论。
long\u字符串的类型是string list->int->string list
。因此,如果将long\u strings
应用于字符串列表,则会得到一个函数:int->string list
。
例如,可以定义
let list=[“1”;“12”;“123”]
let filter\u list=长字符串列表
let=assert(过滤器列表0=[“1”;“12”;“123”])
let=assert(过滤器列表2=[“123”])
然而,在
head::长字符串尾部
您希望long_strings tail
是一个列表。
因此,错误消息
此表达式的类型为int->string list
但应为字符串列表类型的表达式
这说明long\u strings tail
不是一个列表,而是一个接受int
并返回string\u列表的函数
换句话说,您忘记了i
参数。似乎将函数与函数应用程序混为一谈。->
类型是函数,没有它们的类型是应用上述函数的结果。我认为错误表明我产生了不正确的输出类型。我在递归调用中添加了适当的参数,可以继续测试了。感谢您的帮助。您生成的输出类型不正确。OCaml函数通常是“curried”,这意味着您可以省去一些参数,取回一个中间函数,而不是最终答案。如果代码期望最终答案,则此中间函数类型是错误的类型。适应这种模式并不难(IMHO)。
(*Given an INT LIST and INT divide the numbers in the given int
list by the given int and return an (INT * INT) LIST containing
the dividend and the remainder*)
let rec remainders (l: int list) (i: int) : (int * int) list =
match l with
| [] -> []
| head :: tail -> ((head / i), (head mod num)) :: (remainders tail)
;;
This expression has type int -> (int * int) list
but an expression was expected of type (int * int) list