Logo

Programming-Idioms

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

Idiom #126 Multiple return values

Write a function foo that returns a string and a boolean value.

(defn foo
  []
  ["bar" true])
#include <stdbool.h>
typedef struct {
    const char * const a;
    const bool b;
} RetStringBool;

RetStringBool foo() {
    return (RetStringBool) {.a = "Hello", .b = true};
}
#include <tuple>
std::tuple<std::string, bool> foo() {
  return std::make_tuple("someString", true);
}
#include <tuple>
auto foo()
{
    return std::make_tuple("Hello", true);
}
using System;
public Tuple<string, bool> foo_PreCSharp7()
{
    // Only accessed via .Item1 and .Item2
    return new Tuple<string, bool>("string", true);
}

public (string, bool) foo_CSharp7UnnamedTuples()
{
    // Only accessed via .Item1 and .Item2
    return ("string", true);
}

public (string NamedStringArg, bool NamedBooleanArg) foo_CSharp7()
{
    // Can be accessed via .NamedStringArg or .NamedBooleanArg
    return ("string", true);
}
import std.typecons;
auto foo()
{
    return tuple("theString", true);
}
foo() => ['a string', true];
def foo, do: {"bar", true}
subroutine foo(c, b)
  character(len=:), allocatable, intent(out) :: c
  logical, intent(out) :: b
  c = 'string'
  b = .false.
end subroutine foo
func foo() (string, bool) {
	return "Too good to be", true
}
foo :: (String, Bool)   -- optional signature
foo = ("String", True)
const foo = () => ['string', true];
const foo = () => ({string: 'string', bool: true})
static Object[] returnAnything() {
    return new Object[]{"a string", true};
}

public static void main (String[] args) {
    Object[] array = returnAnything();
    System.out.println(array[0]);
    System.out.println(array[1]);
}
private static class Tuple<S, B>
{
	private S s;
	private B b;
	
	public Tuple(S s, B b)
	{
		this.setS(s);
		this.setB(b);
	}
	
	public void setS(S s)
	{
		this.s = s;
	}
	
	public void setB(B b)
	{
		this.b = b;
	}
	
	public S getS()
	{
		return s;
	}
	
	public B getB()
	{
		return b;
	}
}

private static Tuple foo()
{
	return new Tuple<String, Boolean>("value", true);
}
fun foo() : Pair<String, Boolean> = Pair(5, true)

fun useFoo() {
  val a, b = foo()
}
(defun foo () (format t "bar") t)
function foo()
	return "bar", false
end
<?php
function foo() {
    return ['string', FALSE];
}

list($string, $boolean) = foo();
type
  TFooRec = record
    S: String;
    B: Boolean;
  end;

function Foo: TFooRec;
begin
  Result.S := 'Some string';
  Result.B := False;
end;
sub foo {
    return "bar", 1;
}
def foo():
    return 'string', True
def foo
  string, boolean  = "bar", false
  [string, boolean]
end
fn foo() -> (String, bool) {
    (String::from("bar"), true)
}
def foo(): (String, Boolean) = ("bar", true)
(define (foo) 
  (values "foo" #t))
(define (foo) (cons "bar" false))

New implementation...
< >
MLKo