Skip to content

Instantly share code, notes, and snippets.

@FreeMasen
Created February 21, 2019 05:37
Show Gist options
  • Save FreeMasen/7c641964f9ef0c4e04e3ecb1b293e844 to your computer and use it in GitHub Desktop.
Save FreeMasen/7c641964f9ef0c4e04e3ecb1b293e844 to your computer and use it in GitHub Desktop.
Enum Pattern Matching
export function Thing {
constructor(one, two) {
this.one = one;
this.two = two;
}
}
let t1 = new Thing(1, 2);
let t2 = new Thing('one', 'two');
let t3 = addThings(t1, t2); // {one: '1 & one', two: '2 & two'}
function addThings(lhs, rhs) {
let one, two;
if (lhs.one && typeof lhs.one === 'number' && rhs.one && typeof rhs.one ==v 'number') {
one = lhs.one + rhs.one;
} else {
one = `${lhs.one} & ${rhs.one}`
}
if (lhs.two && typeof lhs.two === 'number' && rhs.two && typeof rhs.two === 'number') {
two = lhs.two + rhs.two;
} else {
two = `${lhs.two} & ${rhs.two}`;
}
return new Thing(one, two);
}
struct Thing {
pub one: NumberOrString,
pub two: NumberOrString,
}
enum {
Number(f32),
String(String),
}
fn add_things(lhs: &Thing, rhs: &Thing) -> Thing {
let one = match (&lhs.one, &rhs.one) {
(NumberOrString::String(s1), NumberOrString::String(s2)) => NumberOrString::String(format!("{} & {}", s1, s2)),
(NumberOrString::String(s1), NumberOrString::Number(f2)) => NumberOrString::String(format!("{} & {}", s1, f2)),
(NumberOrString::Nmber(f1), NumberOrString::Number(s2)) => NumberOrString::String(format!("{} & {}", f1, s2)),
(NumberOrString::Number(f1), NumberOrString::Number(f2)) => NumberOrString::Number(f1 + f2),
};
let two = match (&lhs.two, &rhs.two) {
(NumberOrString::String(s1), NumberOrString::String(s2)) => NumberOrString::String(format!("{} & {}", s1, s2)),
(NumberOrString::String(s1), NumberOrString::Number(f2)) => NumberOrString::String(format!("{} & {}", s1, f2)),
(NumberOrString::Nmber(f1), NumberOrString::Number(s2)) => NumberOrString::String(format!("{} & {}", f1, s2)),
(NumberOrString::Number(f1), NumberOrString::Number(f2)) => NumberOrString::Number(f1 + f2),
};
Thing {
one,
two,
}
}
fn main() {
let t1 = Thing {
one: NumberOrString::Number(1),
two: NumberOrString::Number(2),
};
let t2 = Thing {
one: NumberOrString::String("one".to_string()),
two: NumberOrString::String("two".to_string()),
};
let t3 = add_things(t1, t2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment