我必须在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
莫扎特环境将接受代码,但不会返回答案。输入是这样的:{浏览{Max[1 2]}}。我做错了什么?
您没有任何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]}}