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.

fun foo() : Pair<String, Boolean> = Pair(5, true)

fun useFoo() {
  val a, b = foo()
}
#include <stdbool.h>
typedef struct {
    const char * const a;
    const bool b;
} RetStringBool;

RetStringBool foo() {
    return (RetStringBool) {.a = "Hello", .b = true};
}
(defn foo
  []
  ["bar" true])
#include <tuple>
auto foo()
{
    return std::make_tuple("Hello", true);
}
#include <tuple>
std::tuple<std::string, bool> foo() {
  return std::make_tuple("someString", 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]);
}
record Tuple(Object ... a) {}
Tuple foo() {
    return new Tuple("abc", true);
}
Object[] foo() {
    return new Object[] { "abc", true };
}
(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
foo = lambda x: ('abc', 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) (cons "bar" false))
(define (foo) 
  (values "foo" #t))

New implementation...
< >
MLKo