最小和/或最大列表值 [英] Minimum and/or maximum list values

查看:64
本文介绍了最小和/或最大列表值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在练习时,我构建了一个简单的函数,该函数返回列表中的最大值:

While doing practice, I build a simple function that returns the biggest value in a list:

let rec findMax =        // Find maximum value in list
fun l ->
    let rec aux =
        fun l k ->
            match l with  
            | []                ->  k
            | x::xs             ->  if x >= k   then  aux xs x
                                    else aux xs k
    aux l 0

与此同时,我构建了一个类似的函数来查找列表中的最小元素:

Meanwhile, I built a similar function to find the smallest element in a list:

let finMin =        //Find smallest value in list
fun l ->
    let rec aux =
        fun l k ->
            match l with
            | []        ->  k
            | x::xs     ->  if x <= k   then    aux xs x
                            else aux xs k
    aux l 0

这里是问题:我用 k = 0 初始化了两个 aux 函数.这只是部分好:只要列表中没有负值, findMax 即可正常工作.同样, findMin 仅适用于负数.

Here the problem: I initialized both aux functions with k = 0. It is only partially fine: findMax works properly as long as no negative values are in the list. Similarly, findMin works well only with negative numbers.

有效初始化 k 的正确值是什么?有系统相关的价值吗?我应该事先计算吗?我是从错误的角度来解决问题吗?

What should be the proper value to efficiently initialize k? Is there a system-dependant value? Should i previously calculate it? Am I approaching the problem from the wrong side?

PS .我不使用库函数来查找 min max ,因为我正在学习该语言的机制.谢谢你的耐心.

P.S. I do not use library functions to find min and max because I am learning the mechanics of the language. Thanks for your patience.

推荐答案

您可以将列表中的第一项作为最小值或最大值,然后递归比较列表中的其余项.例如:

You can take the first item in the list to be the min or max value and then recurse down the rest of the list comparing as you are going. For example:

let myMax items =
    match items with
     | [] -> failwith "no data"
     | head :: tail ->
        let rec recMax maxSoFar items =
            match items with
                | [] -> maxSoFar
                | head :: tail ->
                    if head > maxSoFar then
                        recMax head tail
                    else
                        recMax maxSoFar tail
        recMax head tail

这篇关于最小和/或最大列表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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