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

问题描述

我想在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 语句为真,如在 **/ /** 中,有没有办法让它做两件事?

解决方法

我想在if~~then中得到两个结果~~[...]

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

(* 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,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

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

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

您还可以阅读以下 StackOverflow 问答:Multiple if statemens in one Function in SML