我如何在 OCaml 中编写一个函数,它接受一个整数列表和 return 具有最大绝对值的元素
How can I write a function in OCaml that takes an integer list and return the element with maximum absolute value
我曾尝试编写代码,但这只是 returns 最大值而不是绝对值。
let rec maxAbsolutenumber_L l =
match l with
|[] -> None
|x::_ -> x
|x::xs -> max x (max_number_list xs)
假设您有一个类似于 max
的函数,除了它 returns 两个值中的绝对值最大者。看来这样可以解决您的问题。
那你就可以开始写这个函数了
附带说明一下,return None
用于某些函数调用和其他调用的整数值是不合法的。它们不是同一类型。
作为另一条旁注,您匹配的第二种情况将匹配所有非空列表。我想你希望它只匹配长度为 1 的列表。这种列表的模式是 [x]
(或者你可以使用 x :: []
,这是等效的)。
更新
这里是定义一个函数的基本结构,里面有另一个(辅助)函数:
let myfunc a b =
let helper x y =
(* Definition of helper *)
in
(* Definition of myfunc with calls to helper *)
这是一个具体的例子,一个 return 是其输入列表中最长字符串的函数:
let longest_string strings =
let max_string a b =
if String.length a >= String.length b then a else b
in
List.fold_left max_string "" strings
下面是常用 max
函数的实现,可能会给您一些编写类似函数的思路:
let max a b =
if a >= b then a else b
我曾尝试编写代码,但这只是 returns 最大值而不是绝对值。
let rec maxAbsolutenumber_L l =
match l with
|[] -> None
|x::_ -> x
|x::xs -> max x (max_number_list xs)
假设您有一个类似于 max
的函数,除了它 returns 两个值中的绝对值最大者。看来这样可以解决您的问题。
那你就可以开始写这个函数了
附带说明一下,return None
用于某些函数调用和其他调用的整数值是不合法的。它们不是同一类型。
作为另一条旁注,您匹配的第二种情况将匹配所有非空列表。我想你希望它只匹配长度为 1 的列表。这种列表的模式是 [x]
(或者你可以使用 x :: []
,这是等效的)。
更新
这里是定义一个函数的基本结构,里面有另一个(辅助)函数:
let myfunc a b =
let helper x y =
(* Definition of helper *)
in
(* Definition of myfunc with calls to helper *)
这是一个具体的例子,一个 return 是其输入列表中最长字符串的函数:
let longest_string strings =
let max_string a b =
if String.length a >= String.length b then a else b
in
List.fold_left max_string "" strings
下面是常用 max
函数的实现,可能会给您一些编写类似函数的思路:
let max a b =
if a >= b then a else b