One problem I wanted to solve was designating "and/or" to its own word; there are two reasons that motivate me: firstly, because "and/or" is so common it deserves its own concept, and secondly, because I hate '/'s and '-'s in my compound words ("and/or" is not a compound, but other compounds usually do have hyphens in them).
Firstly, before we can look at what "orwith" is as a programmatical concept, we must first know what the term means.
The word "orwith" is a compound of English "or" and English "with", where the two ideas unite.
[See definition sites: DeviantArt, Urban Dictionary]
So, what does this word mean? As I said, it can mean "and/or", but formally it is defined as:
conjunction. 1.) Being accompanied with or replaced by something (as specified in the context); and/or.
preposition. 2.) Indicating that both options are possibilities; "or with".
With this knowledge in mind, we can properly formulate an idea of what this may look like.
The first step in turning this idea into a programming concept was to basically make an "AndOr
" enum
:
enum Orwith<T> {
With(T, T),
Or(T)
}
Now, the next thing we need to do is make a function that takes arguments, which represent the two grammatical constituents, and returns a corresponding instance of Orwith
:
impl<T> Orwith<T> {
fn orwith(x:Option<T>, y:Option<T>) -> Self {
match (x, y) {
(Some(vx), Some(vy)) => Self::With(vx, vy),
(Some(v), _) | (_, Some(v)) => Self::Or(v),
_ => /* ??? */
}
}
}
Everything is all fine and well here until we get to the _
case.
Unfortunately, since Rust makes us handle every case, we have to present a new possibility to "and/or" that it wouldn't otherwise have: neither option. To reflect this, the code is changed to:
enum Orwith<T> {
Neither,
With(T, T),
Or(T)
}
With this new Neither
state, the code should look like this:
enum Orwith<T> {
Neither,
With(T, T),
Or(T)
}
impl<T> Orwith<T> {
fn orwith(x:Option<T>, y:Option<T>) -> Self {
match (x, y) {
(Some(vx), Some(vy)) => Self::With(vx, vy),
(Some(v), _) | (_, Some(v)) => Self::Or(v),
_ => Self::Neither
}
}
}
Now we have successfully encapsulated the idea of "one being accompanied, or replaced, by another" in a simple enum
.
To utilize it further, one could utilize it further by giving Orwith
instance methods to operate with the (possible) values contained. For you, I have already done this on GitHub in CalinZBaenen/Orwith
.
Top comments (0)