working on it ...

## Filters

Sort by

Found 13 snippets matching: "multiple return values"

### Return Multiple Type Values from a Function

```Structure MyResults
Public Success As Boolean
Public Result As String
End Structure

Public Function TrySomething(ByVal Parameter As String) As MyResults
Dim NewResult As New MyResults
Try
' Do something and calculate My Result
NewResult.Success=True
NewResult.Result="My Result"
Catch ex As Exception
NewResult.Success=False
NewResult.Result=""
End Try
Return NewResult
End Function```

### Function to simultaneously partition a list into multiple sub-lists based on used-defined criteria. Kind of like a list comprehension with multiple return values.

Function to simultaneously partition a list into multiple sub-lists based on used-defined criteria. Kind of like a list comprehension with multiple return values.: multifilter.py
```def multifilter(seq, *tests, multiple=False):
"""Filters items in a list into sublists corresponding to the
supplied test functions.

:returns: A list of lists of items matching conditions, in order. The last
item in the return value is the list of items that did not
match any condition.

[[items matching condition0],
[items matching condition1],
...
[items matching condition(N-1)],
[non-matching items]]

For example, given a list of numbers, s, you can generate a list of even
numbers and odd numbers by the following:

>>> multifilter(range(10), lambda x: x & 1)
[[1, 3, 5, 7, 9], [0, 2, 4, 6, 8]]

Also, you can do divisible by 2s and 3s like so:

>>> multifilter(range(10), lambda x: divmod(x, 2)[1] == 0,
...                        lambda x: divmod(x, 3)[1] == 0)
[[0, 2, 4, 6, 8], [3, 9], [1, 5, 7]]

If multiple is True, then each element will be tested against all
conditions, resulting in the possibility that the same item will exist in
multiple output arrays. In the above example, even though 6 is divisible by
3, it's not showing up in the second list. By setting multiple to True,
every test applies to each element:

>>> multifilter(range(10), lambda x: divmod(x, 2)[1] == 0,
...                        lambda x: divmod(x, 3)[1] == 0, multiple=True)
[[0, 2, 4, 6, 8], [0, 3, 6, 9], [1, 5, 7]]

"""
results = [[] for i in range(len(tests))]
nonmatching = []
enumerated_tests = list(enumerate(tests))  # for efficiency
for item in seq:
found = False
for i, cond in enumerated_tests:
if cond(item):
results[i].append(item)
found = True
if not multiple:
break
else:
nonmatching.append(item)

results.append(nonmatching)
return results

```

### loco.js -- reusable, chainable, multiple, return values

loco.js -- reusable, chainable, multiple, return values: loco.js
```var Loco = (function LocoMake () {

empty = {}
caboose = null,
Railcar = function Railcar () {
this.deref = this;
};

Railcar.prototype.ended = function ended () {
return this.value === empty;
};

Railcar.prototype.motive = function motive () {
return this.deref.value;
};

Railcar.prototype.couple = function couple () {
var count = arguments.length,
index = 0,
before = this,
after = null,
temp = null;

for (index = 0; index < count; index++) {
after = arguments[index];
temp = after.deref;
after.deref = before.deref;
before.deref = temp;
before = after;
}

return after;
};

Railcar.prototype.motion = function motion (skip) {
var deref = null,
result = this;

skip = (skip === void 0) ? 0 : skip;

do {
if (this.ended()) {
result = null;
break;
}
deref = this.deref;
this.deref = deref.deref;
deref.repool();
} while (skip === null || skip-- > 0);

return result;
};

Railcar.prototype.derail = function derail (skip) {
var deref = this.deref,
result = deref.value;

skip = (skip === void 0) ? 0 : skip;

do {
deref = this.deref;
result = deref.value;
if (!this.motion(0) ||
result = null;
}
} while (skip === null || skip-- > 0);

return result;
};

Railcar.prototype.repool = function repool () {
if (this.value !== empty) {
this.value = empty;
this.deref = caboose;
caboose = this;
}
};

var unpool = function unpool () {
var result = null;
if (caboose) {
result = caboose;
result.deref = result;
caboose = caboose.deref;
} else {
result = new Railcar();
}
return result;
};

return function Loco () {
var count = arguments.length,
index = 0,
before = null,
after = null,
first = null;

if (count) {
first = after = before = unpool();
before.value = arguments[0];
for (index = 1; index < count; index++) {
after = unpool();
after.value = arguments[index];
before.deref = after;
before = after;
}
before.deref = first;
}

return before;
};

}) ();

```

### Allowing multiple return values to include keywords in racket

Allowing multiple return values to include keywords in racket: kw-continuation.rkt
```#lang racket/base

(provide call-with-current-continuation
let/cc
values
call-with-values
)

(require syntax/parse/define
(only-in racket/base [values rkt:values] [let/cc rkt:let/cc]))
(module+ test
(require rackunit))

;; The continuation-mark-key for storing continuations that accept
;; keyword arguments.
(define kw-continuation-key
(make-continuation-mark-key 'keyword-continuation))

;; A version of call-with-current-continuation that finds a
;; continuation that accepts keyword arguments, if it exists.
(define (call-with-current-continuation proc)
(rkt:let/cc k
(call-with-immediate-continuation-mark
kw-continuation-key
proc
k)))

(define-simple-macro (let/cc k:id body:expr ...+)
(call-with-current-continuation (λ (k) body ...)))

;; A version of values that accepts keywords and applies those
;; keywords to the current kw-continuation.
(define values
(make-keyword-procedure
(lambda (kws kw-args . args)
(let/cc k
(keyword-apply k kws kw-args args)))
rkt:values))

;; Is this the right implementation?
(let/cc k
(generator))))

(module+ test
;; test call-with-values and values
(check-equal? (call-with-values
(λ () (values #:a 3))
(λ (#:a a) a))
3)
;; test let/cc
(check-equal? (+ 1 (let/cc k (+ 1000 (k (+ 5 5)))))
11)
;; test let/cc within call-with-values
(check-equal? (+ 1 (call-with-values
(λ () (let/cc k (+ 1000 (k #:a (+ 5 5)))))
(λ (#:a a) (* 4 a))))
41)
)

```

### A proposal for multiple return values

A proposal for multiple return values: MultipleReturnValues.cs
```public class MyClass
{
public void MyMethod()
{
var x, y, z = MyReturnMethod();
Console.WriteLine("{0} {1} {2}", x, y, z);
// 10 Hello <now>

var var1 = MyReturnMethod();
Console.WriteLine(var1);
// 10

string s = MyReturnMethod();
Console.WriteLine(s);
// Hello

string myString, DateTime date = MyReturnMethod();
Console.WriteLine("{0} {1}", myString, date);
// Hello <now>

var v1:y, v2:x = MyReturnMethod();
Console.WriteLine("{0} {1}", v1, v2);
// Hello 10

}

public int, string, DateTime MyReturnMethod()
{
int x = 10;
string y = "Hello";
DateTime z = DateTime.Now;

return x, y, z;
}
}

```

### Multiple return values in Go

Multiple return values in Go: swap.go
```package main

import "fmt"

func swap(a, b int) (int, int) {

_a := a
_b := b

a, b = _b, _a

return a, b
}

func main() {
fmt.Println(swap(1, 5))
}

```

### Multiple return values from function ( < C++17 )

Multiple return values from function (
```#include <tuple>

{
return std::make_tuple(42, 9001);
}

int a=0, b=0;

```

### Getting multiple return values in C. Explains structs, typedefs, and pointers.

Getting multiple return values in C. Explains structs, typedefs, and pointers.: multiple_return_values.c
```#include <stdio.h>

// =====  Our Types  =====
// A struct is a single type (like an int)
// that contains other types, and gives them names
struct numbers {
int first;
int second;
};

// This is all one expression, it's on multiple lines for readability
typedef          // means to make a new type
struct numbers // it is defined in terms of types we already know, in this case, the struct we just defined
Numbers;       // its name is `Numbers`, so it's basically an alias for for struct (we do this b/c it's more convenient to type and read)

// =====  Function Declarations =====
// so you can go view them as they are used, rather than as they are declared
Numbers new_nums();
void print_numbers(char*, Numbers);
void update_nums_by_value(Numbers);
void update_nums_by_reference(Numbers*);

// =====  Using the struct  =====
int main (int argc, char const *argv[]) {
// ----- Understanding the struct -----
// The struct is literally just two ints, adjacent to eachother in memory.
puts("Understanding the struct");
printf("  sizeof(int)     -> %d\n", (int)sizeof(int));
printf("  sizeof(Numbers) -> %d\n", (int)sizeof(Numbers)); // 2x as big b/c it's literally just 2 ints side by side

// when we use an attribute name like `n.first`, it will map to the offset of that attribute.
Numbers n = {100, 123}; // <-- fancy way to initialize
printf("  first           -> %d\n", n.first);
printf("  second          -> %d\n", n.second);
puts("");

// ----- Example 1: Returning a struct directly -----
// `my_n` is in our stack, it copies its value from the return location of `new_nums`
// so after the `new_nums` returns, there will have been 3 different Numbers structs:
//   1. the `n` inside new_nums,
//   2. the return value of `new_nums`
//   3. and the `my_n` here
Numbers my_n = new_nums();
print_numbers("Returned from `new_nums()`", my_n);

// ----- Example 2: The problem with passing values -----
// Lets update the value. There's a problem here
// see if you can figure out what it is before reading the next example :)
update_nums_by_value(my_n);
print_numbers("After `update_nums_by_value(my_n)`", my_n);

// ----- Example 3: The solution is to pass a reference -----
// Because `update_nums_by_value` takes a `Number` on the stack,
//     we are copying the memory at `my_n` into the memory at it's `n` argument.
//     So the struct it is updating is at a different memory locaiton,
//     its data came from ours, but it's not ours
// What we need to do is pass it the memory location of our struct
//     then have it go to that memory location and update the values there.
//     we pass the location of `my_n` rather than its value by using the `&`.
//     The "location" is often called the "address" or "reference"
// An analogy: If you haven't seen these before, you can think of it as the difference
//     between giving your friend a clone of yourself, and giving them your phone number.
//     it's more convenient to have the clone around, but it's expensive to clone yourself,
//     and whatever conversations they have with the clone will be the clone's conversations, not yours.
//     But if you give them your phone number, then you're not as immediate as the clone,
//     but they can still have conversations with you, they just have to call the number first,
//     and these are conversations that *you* are having, not some clone that's going to die as soon as the method returns
//     ...okay, that analogy might have broken down at the end there :/
update_nums_by_reference(&my_n);
print_numbers("After `update_nums_by_reference(&my_n)`", my_n);

// ----- A few gotchas to watch out for -----
// Don't return a reference to a variable declared in your function
//   If your function finds the values and wants to return them as a pointer,
//   you need to actually allocate that memory on the heap (the `malloc` function),
//   don't return a pointer to a local variable, because it's on the stack,
//   and as soon as you return from the function, its memory is at risk of being overridden.
//   This will result in either its values getting really wonky and changing in unexplainable ways over time,
//   or in a segmentation fault.
// It's often more convenient to have the caller pass a reference, even if it has no meaning until after the function
//   Memory management is annoying.
//   If you let the caller give you the memory, then your function doesn't have to deal with all the allocation.
//   And everyone knows who is responsible for making sure that memory gets handled correctly: the caller.
//   This reduces the probability of a memory leak.
//   And it's likely that the caller can just make a local variable on the stack, and do everything it needs with that.
//   No need to off into the heap at all!
return 0;
}

// =====  The Functions  =====

void print_numbers(char* title, Numbers n) {
printf("%s\n  first  -> %d\n  second -> %d\n\n", title, n.first, n.second);
}

Numbers new_nums() {
Numbers n;    // A new varable on the stack named `n`

n.first  = 1; // The dot in `n.first` means that within the n's memory,
n.second = 2; // we're dealing with the subset of memory that we named `first`

return n;     // Copy memory at `n` to the memory treated as the return value
}

void update_nums_by_value(Numbers n) {
n.first  = 11;
n.second = 22;
}

// The asterisk in a declaration means that we're receiving the memory address of the type
// So the asterisk in `Numbers* n` means that n is the address of a `Numbers`
void update_nums_by_reference(Numbers* n) {
// Because it's an address, we have to go look it up before doing anything with it
// In the above analogy, this is like calling you on the phone
(*n).first = 11;

// That's what we want to do, but it's annoying to type that, and in reality,
// we do this sort of thing almost all of the time, and directly talk to structs very infrequently.
// So we have the arrow syntax to mean "go to this location and access this attribute"
n->second = 22;  // this is the same as `(*n).second = 22`
}

```

### multiple return values by a declared transport type

multiple return values by a declared transport type: MultipleReturnByDeclaredTrasportType.cs
```public struct TallyResult { public int Sum; public int Count; }
public TallyResult Tally(IEnumerable<int> values) { ... }

var t = Tally(myValues);
Console.WriteLine(\$"Sum: {t.Sum}, count: {t.Count}");

```

### multiple return values by out parameters

multiple return values by out parameters: MultipleReturnByOutParameter.cs
```public void Tally(IEnumerable<int> values, out int sum, out int count) { ... }

int s, c;
Tally(myValues, out s, out c);
Console.WriteLine(\$"Sum: {s}, count: {c}");

```
• Public Snippets
• Channels Snippets