首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >递归调用。如何以及为什么返回最大值?(新泽西州标准ML )

递归调用。如何以及为什么返回最大值?(新泽西州标准ML )
EN

Stack Overflow用户
提问于 2018-08-11 18:27:52
回答 1查看 121关注 0票数 1

这是很糟糕的代码,但它是有效的。我只是想知道这个递归调用如何判断哪个数字是最大的/max?试着像我7岁那样解释:)

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2018-08-11 23:09:48

首先阅读nulltlhd。一些提示让你开始吧。

代码语言:javascript
复制
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)`
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51798740

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档