问题描述
我正在处理家庭作业问题,通常,我对为什么会发生错误有所了解,但是,对于这两个问题,我不知道发生了什么。我不确定是模式匹配还是模式匹配后我要解决的问题。
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)
This expression has type int -> string list
but an expression was expected of type string list
另一个类似的问题...
(*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
解决方法
您缺少争论。 long_strings
的类型为string list -> int -> string list
。因此,如果将long_strings
应用于字符串列表,则会得到一个函数:int -> string list
。
例如,可以定义
let list = ["1"; "12"; "123"]
let filter_list = long_strings list
let _ = assert ( filter_list 0 = ["1"; "12"; "123"] )
let _ = assert ( filter_list 2 = ["123"] )
但是,在
head :: long_strings tail
您期望long_strings tail
是一个列表。
因此,错误消息
此表达式的类型为int->字符串列表 但是应该使用字符串列表类型的表达式
告诉您long_strings tail
不是列表,而是一个包含int
并返回string_list
的函数。
换句话说,您忘记了i
参数。