有没有办法在 if - else 语句中放置两个动作作为 then 的结果?

Is there a way to put two actions as a result of then in the if - else statement?

我想在if~~then~~中做两个结果。 例如,

fun count (x,[]) = 0
| count (x,y::ys) =
val cnt = 0
if x mod y = 0 then **/ cnt+1 and count(x,y/2) /**
else count (x-y,ys)

如果 if 语句为真,如 **/ /**,有没有办法让它做两件事?

I want to make two results in if~~then~~ [...]

您可以使用元组创建一个 return 有两个结果的函数,例如:

(* Calculate the two solutions of a 2nd degree polynomial *)
fun poly (a, b, c) =
    let val d = b*b - 4.0*a*c
        val sqrt_d = Math.sqrt d
    in ( (~b + sqrt_d) / (2.0*a), (~b - sqrt_d) / (2.0*a) )
    end

您还可以根据某些标准提供两种不同的结果,例如:

fun poly (a, b, c) =
    let val d = b*b - 4.0*a*c
        val sqrt_d = Math.sqrt d
        val root_1 = (~b + sqrt_d) / (2.0*a)
        val root_2 = (~b - sqrt_d) / (2.0*a)
    in
      if root_1 > root_2
      then (root_1, root_2)
      else (root_2, root_1)
    end

但是如果你需要一个函数在一种情况下 return 一个结果,在另一种情况下两个结果,你需要将结果包装在一个 return 类型中,可以容纳 或者一个或者两个值,例如:

datatype ('a, 'b) one_or_two = One of 'a | Two of 'a * 'b

datatype item = Apple | Lamp | Knife

val gen = Random.newgen ()
fun loot () =
    if Random.random gen > 0.90
    then Two (Lamp, Knife)
    else One Apple

您还可以阅读以下 Whosebug 问答: