typestar

where and merge in Fortran

Conditional assignment over whole arrays: where picks elements, merge picks values.

program where_masks
    implicit none
    real :: temps(7) = [61.0, 68.0, 74.0, 79.0, 72.0, 65.0, 58.0]
    real :: adjusted(7)

    ! where assigns only where the mask holds; elsewhere covers the rest.
    where (temps > 70.0)
        adjusted = temps - 2.0
    elsewhere
        adjusted = temps
    end where

    print *, "adjusted: ", adjusted
    ! merge is the one-line version: value-if-true, value-if-false, mask.
    print *, "capped:   ", merge(70.0, temps, temps > 70.0)
end program where_masks

How it works

  1. where (temps > 70.0) assigns only where the mask holds.
  2. elsewhere handles the rest, and end where closes the construct.
  3. merge(70.0, temps, mask) is the expression form: if-true, if-false, mask.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
450
Tokens
75
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 69 seconds.

Type this snippet

Step 2 of 3 in Whole-array thinking, step 11 of 27 in Language basics.

← Previous Next →