Tuples are a lightweight way to group a fixed set of arbitrary types of data together.
A tuple doesn't have a particular name; naming a data structure turns it into a struct.
A tuple's fields don't have names; they are accessed by means of destructuring or by position.
Tuples are always created with a tuple expression:
// pointless but legal
let unit = ();
// single element
let single_element = ("note the comma",);
// two element
let two_element = (123, "elements can be of differing types");
Tuples can have an arbitrary number of elements.
It is possible to access the elements of a tuple by destructuring. This just means assigning variable names to the individual elements of the tuple, consuming it.
let (elem1, _elem2) = two_element;
assert_eq!(elem1, 123);
You are working on a game targeting a low-power embedded system and need to write several convenience traits which will be used by other parts of the game.
A quotient is the output of a division.
fn divmod(self: @u16, divisor: u16) -> (u16, u16)
Example:
let dividend: u16 = 10;
assert_eq!(dividend.divmod(3), (3, 1));
This will be helpful to enable a screen-buffer optimization, your boss promises.
trait EvensTrait<T> {
fn evens(self: @Array<T>) -> Array<T>;
}
Examples:
let arr: Array<u16> = array![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
assert_eq!(arr.evens(), array![0, 2, 4, 6, 8]);
let arr: Array<u16> = array![1, 2, 3, 4, 5, 6, 7, 8, 9];
assert_eq!(arr.evens(), array![1, 3, 5, 7, 9]);
For mapping convenience, you have a tuple type Position:
type Position = (i16, i16);
You need to implement a method manhattan on Position which returns the
manhattan distance of that position from the origin (let p: Position = (0, 0)).
trait PositionTrait {
fn manhattan(self: @Position) -> i16
}
Example:
let p: Position = (3, 4);
assert_eq!(p.manhattan(), 7);
Sign up to Exercism to learn and master Cairo with 25 concepts68 exercises, and real human mentoring, all for free.