Skip to content

Instantly share code, notes, and snippets.

@gavinking
Last active December 27, 2015 11:39
Show Gist options
  • Save gavinking/7319877 to your computer and use it in GitHub Desktop.
Save gavinking/7319877 to your computer and use it in GitHub Desktop.
We can use tuples to define functions with multiple return values. This code example shows how we can use the spread operator and function composition with such functions.
//a function that produces a tuple
[String, String?, String] parseName(String name) {
value it = name.split().iterator();
"first name is required"
assert (is String first = it.next());
"last name is required"
assert (is String second = it.next());
if (is String third = it.next()) {
return [first, second, third];
}
else {
return [first, null, second];
}
}
//a function with multiple parameters
String greeting(String first, String? middle, String last) =>
"Greetings, ``first`` ``last``!";
void demoFunctionComposition() {
//the * operator "spreads" the tuple result
//of parseName() over the parameters of
//greeting
print(greeting(*parseName("John Doe")));
//but what if we want to compose parseName()
//and greeting() without providing arguments
//up front? Well, we can use compose() and
//unflatten()
value greet = compose(print,
compose(unflatten(greeting), parseName));
greet("Jane Doe");
//so we could actually re-express the first
//example in terms of unflatten()
print(unflatten(greeting)(parseName("Jean Doe")));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment