这是很糟糕的代码,但它是有效的。我只是想知道这个递归调用如何判断哪个数字是最大的/max?试着像我7岁那样解释:)
fun badmax (xs : int list)=
if null xs
then 0
else if null (tl xs)
then hd xs
else if hd xs > badmax(tl xs)
then hd xs
else badmax(tl xs)
发布于 2018-08-11 23:09:48
fun badmax (xs : int list)=
if null xs <- If the list is empty, return 0
then 0
else if null (tl xs) <- If there is nothing returned by `null (tl xs)`,
we will return hd xs.
Q: Are you sure there is anything left in `hd xs`?
Note that if there is nothing left, calling
`hd xs` will raise exception. How can you be sure?
then hd xs
else if hd xs > badmax(tl xs) Q: What are we comparing here?
Think about what does `badmax(tl xs)`
return and why would we return `hd xs`
if the condition is satisfied.
Again, ask why `hd xs` and `tl xs` are legal.
then hd xs
else badmax(tl xs) Q: Why would we want to return `badmax(tl xs)`
https://stackoverflow.com/questions/51798740
复制相似问题