递归调用,如何和为什么返回最大值?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (20)

这是很糟糕的代码,但有效。我只是想知道这个递归调用是如何判断哪个数字是最大/最大的?试着解释一下:

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)
提问于
用户回答回答于

首先读取nulltl,和hd

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)`

所属标签

可能回答问题的人

  • 不吃貓的鱼oo

    5 粉丝466 提问6 回答
  • Richel

    8 粉丝0 提问4 回答
  • 骑牛看晨曦

    4 粉丝522 提问3 回答
  • 发条丶魔灵1

    6 粉丝525 提问3 回答

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励