# Select case to set a variable

Here is a thought inspired by the conditional expressions threads. I usually use `select case` to set a variable based on the value of another variable or expression, for example

``````select case (dist)
case ("normal")  ; yy = one_over_sqrt_two_pi * exp(-0.5*xx**2)
case ("Laplace") ; yy = 1/(sqrt_two)*exp(-sqrt_two*abs(xx))
case ("sech")    ; yy = sech(pi_over_2*xx)/2
case ("t5")      ; yy = student_t_density(xx,dof=5.0_dp,mu=0.0_dp,xsd=1.0_dp)
case ("t10")     ; yy = student_t_density(xx,dof=10.0_dp,mu=0.0_dp,xsd=1.0_dp)
case default     ; yy = bad_real
end select
``````

Sometimes the `case` list is very long, and the programmer may set a variable other than yy by mistake. I’d like to be able to write something like

``````yy = select case (dist)
case ("normal")  : one_over_sqrt_two_pi * exp(-0.5*xx**2)
case ("Laplace") : 1/(sqrt_two)*exp(-sqrt_two*abs(xx))
case ("sech")    : sech(pi_over_2*xx)/2
case ("t5")      : student_t_density(xx,dof=5.0_dp,mu=0.0_dp,xsd=1.0_dp)
case ("t10")     : student_t_density(xx,dof=10.0_dp,mu=0.0_dp,xsd=1.0_dp)
end select
``````

where it is guaranteed that `yy` is set. `Select case` can be viewed as a restricted form of an `if-then-elseif-endif` block that depends on a single expression, and I think it would be convenient and safer to have a further restricted form that sets a single variable.

1 Like

I really like this idea, and suggested something similar on the GitHub.

This is a problem with the “keyword” form of conditional expressions, in my view. If an if-statement can return a value, why not `select case`, or `block`, or a do-loop? That’s probably doable, but it would make for a very different language.

1 Like

This idea is very similar to pattern matching in Scala. I’ve talked to some people that think this is the best feature of Scala.

1 Like

A shortcoming of the “keyword” form is that it “looks” a lot like an IF construct. Insert a few strategically located “;” characters and it IS an IF construct. If you don’t like that aspect, I can refer you to the C Lang Retail Shop down the street where they have a ternary operator syntax that has been time-tested for decades, and still available. (cond ? expr_if_true : expr_if_false).

1 Like