Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #267 Pass string to argument that can be of any type

Declare an argument x to a procedure foo that can be of any type. If the type of the argument is a string, print it, otherwise print "Nothing."

Test by passing "Hello, world!" and 42 to the procedure.

use Scalar::Util qw(looks_like_number);
sub foo {
    my ($s, $x) = @_;
    return 'is undefined'   if not defined $x;
    return 'is a reference' if ref $x ne '';
    return 'is a number'    if looks_like_number $s;
    return 'is a string';
}
use v5.10;
useScalar::Util 'looks_like_number';
sub foo {
    my ($x) = @_;
    return 'Nothing' if ref $x ne '' or looks_like_number($x);   
    return $x;
}

$\ = "\n"; # print with newline
say foo( [] );
say foo( 42 );
say foo( 'Hello World' );
(defn foo [x]
  (println (if (string? x) x "Nothing.")))

(foo "Hello, world!")
(foo 42)
using System;
void foo<T>(T x)
{
    if (x is string s)
    {
        Console.WriteLine(s);
    }
    else
    {
        Console.WriteLine("Nothing.");
    }
}

foo("Hello, world!");
foo(42);
using System;
void foo(object x)
{
    if (x is string s)
    {
        Console.WriteLine(s);
    }
    else
    {
        Console.WriteLine("Nothing.");
    }
}

foo("Hello, world!");
foo(42);
foo(x) => print(x is String ? x : 'Nothing.');

foo('Hello, world!');
foo(42);
program main
  call foo("Hello, world!")
  call foo(42)
contains
  subroutine foo(x)
    class(*), intent(in) :: x
    select type(x)
    type is (character(len=*))
       write (*,'(A)') x
    class default
       write (*,'(A)') "Nothing."
    end select
  end subroutine foo
end program main
import "fmt"
func foo(x any) {
	if s, ok := x.(string); ok {
		fmt.Println(s)
	} else {
		fmt.Println("Nothing.")
	}
}

func main() {
	foo("Hello, world!")
	foo(42)
}
function foo(x) {
  console.log(typeof x == 'string' ? x : 'Nothing.')
}

foo('Hello, world!')
foo(42)
    public static void main(String[] args) {
        foo("Hello, world!");
        foo(42);
    }

    private static void foo(Object x) {
        if (x instanceof String) {
            System.out.println(x);
        } else {
            System.out.println("Nothing.");
        }
    }
import static java.lang.System.out;
<T> void foo(T x) {
    if (x instanceof String) out.println(x);
    else out.println("Nothing.");
}
import static java.lang.System.out;
interface F<T> { void set(T x); }
F<Object> foo = x -> {
    if (x instanceof String) out.println(x);
    else out.println("Nothing.");
};
foo.set("Hello, world!");
foo.set(42);
variants
procedure foo(const x: variant);
begin
  case (TVarData(x).vType and varTypeMask) of
    varOleStr, varUString, varString: writeln(x);
    otherwise writeln('Nothing');
  end;
end;

begin
  foo('Hello World');
  foo(42);
end.
def foo(x):
    if isinstance(x, str):
        print(x)
    else:
        print('Nothing.')
    return

foo('Hello, world!')
foo(42)
def foo(x)
  puts x.class == String ? x : "Nothing"
end

foo("Hello, world")
foo(42)
use std::any::Any;
fn foo(x: &dyn Any) {
    if let Some(s) = x.downcast_ref::<String>() {
        println!("{}", s);
    } else {
        println!("Nothing")
    }
}

fn main() {
    foo(&"Hello, world!".to_owned());
    foo(&42);
}
(define (foo x)
  (displayln
   (if (string? x)
       x
       "Nothing")))

(foo "Hello, world!")
(foo 42)

New implementation...
< >
tkoenig