【问题标题】:Find the max in a list - OZ在列表中查找最大值 - OZ
【发布时间】:2015-10-11 00:14:04
【问题描述】:

我必须在 Oz 中编写一个程序,该程序将返回列表中的最大整数。到目前为止,我的代码如下所示:

    declare
    proc  {Max Xs K}
       case Xs
       of nil then K = 0
       [] X|Xr then
          local M in
              if M < X then M = X end
              {Max Xr K}
              K = M
          end
       end
    end

Mozart 环境将接受代码但不会返回答案。输入如下所示: {浏览{最大 [1 2]}}。我做错了什么?

【问题讨论】:

  • “Emacs 将接受代码”是什么意思?这个问题和 Emacs 有什么关系?

标签: list max oz mozart


【解决方案1】:

您没有任何 else 子句,那么您如何比较 M 和 X ? M在开始时没有值。我还会使用函数来使其更简单,顺便说一句,您离解决方案不远:

local
 fun {MaxList L1}
  case L1
  of nil then 0
  [] X|Xr then
   if {MaxList Xr}>X then {MaxList Xr}
    else X
   end
  end
 end
in
 {Browse {MaxList [1 2 3 4 3]}}
end

或者您可以按照 Rosetta 代码中的建议以更复杂但更简洁的方式进行操作:

declare
  fun {Maximum X|Xr}         %% pattern-match on argument to make sure the list is not empty
     {FoldL Xr Value.max X}  %% fold the binary function Value.max over the list
  end
in
  {Show {Maximum [1 2 3 4 3]}} 

【讨论】:

    猜你喜欢
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 2023-01-02
    • 2017-09-19
    • 1970-01-01
    • 2014-10-06
    • 2021-11-26
    • 1970-01-01
    相关资源
    最近更新 更多