作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
We want to find the largest value in a given nonempty list of integers. Then we have to compare elements in the list. Since data values are given as a sequence, we can do comparisons from the beginning or from the end of the list. Define in both ways. a) comparison from the beginning b) comparison from the end (How can we do this when data values are in a list?)
我所做的就是从头开始比较,找出最大的数字。
我怎样才能从最后做到这一点?我应该应用什么逻辑?
这是我从头开始进行比较的代码。
- fun largest[x] = x
= | largest(x::y::xs) =
= if x>y then largest(x::xs) else largest(y::xs)
= | largest[] = 0;
val largest = fn : int list -> int
output
- largest [1,4,2,3,6,5,4,6,7];
val it = 7 : int
最佳答案
在您的函数中,将比较列表的前两个元素,并将较大的值与其余元素进行比较。我认为从尾开始比较的意思是先尝试找到列表尾部最大的数,然后再与头元素进行比较。
fun largest [] = raise Empty
| largest [x] = x
| largest (x::xs) =
let
val y = largest xs
in
if x > y then x else y
end
虽然不是必需的,但为了完整性,您应该处理空列表的情况。如果使用 max
函数,您可以缩短函数。
fun largest [] = raise Empty
| largest [x] = x
| largest (x::xs) = max(x, largest xs)
说实话,我更喜欢你的尾递归版本(它不会破坏大列表上的堆栈)。正如其他答案所示,我的函数可以重写为尾递归,但它肯定比您的函数更复杂。
关于list - 如何在SML中找到列表中最大的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12522803/
我是一名优秀的程序员,十分优秀!