如何解决函数中的整数列表
这个函数是否接受两个 int 列表“x 和 y”并返回一个 y-x 的 int 列表?
let rec fun4 (l: int list) :int list =
begin match l with | [] -> []
| [_] -> []
| x::y::rest -> (y-x)::(fun4 (y::rest))
end
解决方法
列表被定义为递归类型:
type 'a list =
| [] of 'a list (* the empty case *)
| ( :: ) of 'a * 'a list
所以你基本上有两个构造函数:[]
是空列表,x :: other_list
是一个以 x
为头,other_list
为尾的列表。使用这些构造函数可以轻松定义列表:[0; 1; 2; 3]
与 0 :: 1 :: 2 :: 3
和 (::) (0,(::) (1,(::) (2,(::) (3,[]))))
完全相同(读起来不太愉快)。
递归代数类型,这里我们有和([]
和(::)
)和乘积(('a * 'a list)
)的合取,结合模式匹配可以描述各种常见的数据结构,以及它们的消费、修改等功能。
在您的示例中,您使用模式匹配来解构列表:
let rec fun4 my_list =
match my_list with
(* if my list is empty,I can't process the function so
I return the empty list *)
| [] -> []
(* if my list my list has only one element,I can't process the function
so,like in the previouse case,I return the empty list *)
| [ _ ] -> []
(* Here is the last case of the function,If I almost have two elements in the
list. Remember that empty list is also a list ! *)
| x :: y :: rest -> (y - x) :: (fun4 (y :: rest))
如您所见,递归代数数据类型与模式匹配相结合,对于描述数据结构(如列表以及许多其他数据结构)和编写使用这些数据结构的函数非常有效。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。