我有一个Ocaml函数有一个问题,该函数需要两个输入,并且应该ti给出特定的输出

问题描述

我正在处理家庭作业问题,通常,我对为什么会发生错误有所了解,但是,对于这两个问题,我不知道发生了什么。我不确定是模式匹配还是模式匹配后我要解决的问题。

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参数。