我试图想出一个函数,它将3个数字作为输入并返回其中最大的数字。我的代码如下:
fun max3(a,b,c)=
if a >= b andalso a >= c then a
else if b >= a andalso b >= c then b
else if c >= a andalso c >= b then c;
但是,我收到以下错误:
Error: syntax error: inserting LET
Error: syntax error: replacing SEMICOLON with EQUALOP
Error: syntax error found at EOF
我做错了吗?
答案 0 :(得分:1)
每次有if
时,您需要then
和else
。您可以通过更改缩进的方式来了解这是如何成为问题的。
fun max3(a,b,c)=
if a >= b andalso a >= c
then a
else if b >= a andalso b >= c
then b
else if c >= a andalso c >= b
then c
(* notice how there is no else here? *)
;
但是,您可以大量简化逻辑:
fun max3(a,b,c)=
if a >= b andalso a >= c then
(* a is the largest of a, b and c *)
a
else
(* a is not the largest, so either b or c is the largest *)
if b >= c then
(* b is the largest of the two *)
b
else
(* c is the largest of the two *)
c
答案 1 :(得分:0)
我会将此问题减少到已经解决的问题:
fun max3 (a, b, c) = max2 (a, max2 (b, c))
,其中
fun max2 (a, b) = if a > b then a else b
或只是
val max2 = Int.max