Logo

Programming-Idioms

  • Pascal
  • Rust
  • Java
  • Fortran

Idiom #225 Declare and use an optional argument

Declare an optional integer argument x to procedure f, printing out "Present" and its value if it is present, "Not present" otherwise

subroutine f(x)
  integer, optional :: x
  if (present(x)) then
    print *,"Present", x
  else
    print *,"Not present"
  end if
end subroutine f
   
procedure f; overload;
begin
  writeln('not present');
end;

procedure f(x: integer); overload;
begin
  writeln('present');
end;

Not exactly what tkoenig meant, but can be resolved using overloading (same procedure name with different parameter list) quite easily.
fn f(x: Option<()>) {
    match x {
        Some(x) => println!("Present {}", x),
        None => println!("Not present"),
    }
}
import static java.lang.System.out;
void f() { set(null); }
void f(int x) { set(x); }
private void set(Integer t) {
    if (t != null) out.println("Present");
    else out.println("Not present");
}

In Java, "overloading" a method is the typical way to create an optional parameter.
import static java.lang.System.out;
void f(int ... x) {
    if (x.length != 0) out.println("Present");
    else out.println("Not present");
}

"... The method can then be called with any number of that parameter, including none."
private void f(Integer x) {
    if (x != null) {
        System.out.println("Present " + x);
    } else {
        System.out.println("Not present");
    }
}

The caller always needs to provide a first argument, which may be null.
(defn f [& [x]]
  (if (integer? x)
    (println "Present" x)
    (println "Not present")))

Optional argument with positional parameters

New implementation...
< >
tkoenig