如何从带有两个参数的函数的列表中获取最大值? [英] How do I get the max value from a list with a function that takes two arguments?

查看:224
本文介绍了如何从带有两个参数的函数的列表中获取最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义函数max2,该函数将两个整数作为参数并返回其中最大的一个.

Define the function max2 that takes two integers as arguments and returns the largest of them.

我这样做:let max2 x y = if x < y then y else x我相信这是正确的

I did this: let max2 x y = if x < y then y else x this I belive is correct

然后定义函数max_list,该函数通过调用max2返回非空整数列表中的最大元素.对于空列表,它应该中止并显示一条错误消息(引发异常)

Then define the function max_list that returns the largest of the elements in a nonempty list of integers by calling max2. For the empty list, it should abort with an error message ( raising an exception)

我这样做了:let list = [3;4] let max_list = if list.IsEmpty then 0 else max2 list.Item(0) list.Item(1),但是如果列表多于两个元素,这将无法工作.我不想使用任何面向对象的东西.正确答案是什么?

I did this: let list = [3;4] let max_list = if list.IsEmpty then 0 else max2 list.Item(0) list.Item(1) but this wont work if the list is more then two elements. I dont want to use any object-orientated stuff. What is the correct answer?

推荐答案

一个简单的递归解决方案:

A simple recursive solution:

let max2 x y = if x < y then y else x

let max_list list =
  let rec loop hi list = 
     match list with 
     | h::t -> let hi = max2 h hi
               loop hi t
     | []   -> hi
  match list with
  | h::t -> loop h t
  | []   -> invalidArg "list" "Empty list"

在FSI中测试:

> max_list [3;4;5;1;2;9;0];;
val it : int = 9

对于列表中的每个元素,将其与上一个最高的元素("hi")进行比较.将新的最高值和列表的其余部分传递到循环函数中,直到输入列表为空.然后只需返回"hi"即可.

For each element in the list, compare it to the previous highest ('hi'). Pass the new highest and the rest of the list into the loop function, until the input list is empty. Then just return 'hi'.

这篇关于如何从带有两个参数的函数的列表中获取最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆