File tree Expand file tree Collapse file tree 4 files changed +68
-0
lines changed
Expand file tree Collapse file tree 4 files changed +68
-0
lines changed Original file line number Diff line number Diff line change @@ -209,4 +209,15 @@ describe Option do
209209 y4 = None (Int32 )[]
210210 x4.xor(y4).should eq(None (Int32 )[])
211211 end
212+
213+ it " <=>" do
214+ a = None (Int32 )[]
215+ b = Some [0 ]
216+ c = Some [1 ]
217+
218+ (a < b).should be_true
219+ (b < c).should be_true
220+
221+ expect_raises(Option ::Uncomparable ) { a <=> 0 }
222+ end
212223end
Original file line number Diff line number Diff line change @@ -217,4 +217,23 @@ describe Result do
217217 y = Err (Int32 , String )[" foo" ]
218218 y.unwrap_or_else { |e | e.size }.should eq(3 )
219219 end
220+
221+ it " <=>" do
222+ x1 = Ok (Int32 , String )[1 ]
223+ y1 = Err (Int32 , String )[" error" ]
224+
225+ (x1 < y1).should be_true
226+
227+ x2 = Ok (Int32 , String )[0 ]
228+ y2 = Ok (Int32 , String )[1 ]
229+
230+ (x2 < y2).should be_true
231+
232+ x3 = Err (Int32 , Int32 )[0 ]
233+ y3 = Err (Int32 , Int32 )[1 ]
234+
235+ (x3 < y3).should be_true
236+
237+ expect_raises(Result ::Uncomparable ) { x1 <=> 0 }
238+ end
220239end
Original file line number Diff line number Diff line change @@ -3,6 +3,8 @@ require "./result"
33abstract struct Option (T )
44 class UnwrapNone < Exception ; end
55
6+ class Uncomparable < Exception ; end
7+
68 macro inherited
79 {% type = @type .name(generic_args: false ).stringify % }
810
@@ -265,6 +267,23 @@ abstract struct Option(T)
265267 end
266268 end
267269 end
270+
271+ include Comparable (self )
272+
273+ def <=> (other ) : Int32
274+ case {self , other}
275+ when {Some , Some }
276+ self .unwrap <=> other.unwrap
277+ when {Some , None }
278+ 1
279+ when {None , Some }
280+ -1
281+ when {None , None }
282+ 0
283+ else
284+ raise Uncomparable .new(" Cannot compare Option with #{ other.class } " )
285+ end
286+ end
268287end
269288
270289struct Some (T ) < Option (T )
Original file line number Diff line number Diff line change @@ -3,6 +3,8 @@ abstract struct Result(T, E)
33
44 class UnwrapErrOnOk < Exception ; end
55
6+ class Uncomparable < Exception ; end
7+
68 macro inherited
79 {% type = @type .name(generic_args: false ).stringify % }
810
@@ -270,6 +272,23 @@ abstract struct Result(T, E)
270272 {% end % }
271273 end
272274 end
275+
276+ include Comparable (self )
277+
278+ def <=> (other ) : Int32
279+ case {self , other}
280+ when {Ok , Ok }
281+ self .unwrap <=> other.unwrap
282+ when {Ok , Err }
283+ -1
284+ when {Err , Ok }
285+ 1
286+ when {Err , Err }
287+ self .unwrap_err <=> other.unwrap_err
288+ else
289+ raise Uncomparable .new(" Cannot compare Result with #{ other.class } " )
290+ end
291+ end
273292end
274293
275294struct Ok (T , E ) < Result (T , E )
You can’t perform that action at this time.
0 commit comments