Created
September 21, 2016 19:35
-
-
Save yreynhout/bb77effc8bc46a595058ea65c4e958de to your computer and use it in GitHub Desktop.
Did you get that one?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Value objects à la F# | |
type Position = | |
struct | |
val Value : int64 | |
new (value) = { Value = value } then | |
if value < 0L then invalidArg "value" "The value must be greater than or equal to 0." | |
member this.Next = | |
if this.Value = Int64.MaxValue then | |
invalidOp (sprintf "There's no next value beyond %d" Int64.MaxValue) | |
new Position(this.Value + 1L) | |
static member (+) (left: Position, right: Position) = | |
new Position(left.Value + right.Value) | |
static member (+) (left: Position, right: int32) = | |
new Position(left.Value + int64(right)) | |
static member (+) (left: Position, right: int64) = | |
new Position(left.Value + right) | |
static member Zero = new Position(0L) | |
static member One = new Position(1L) | |
end | |
//Usage | |
let position = Position.Zero | |
let range = seq { position .. position + 5 } // nice | |
/* | |
** I started out without the (+) operator, compiler started complaining at "seq { position" | |
** that I was missing that operator overload. Once fixed it started complaining at "seq { position" | |
** again, now that the get_One operator was missing. Ruben pointed me in the right direction, | |
** which seems obvious in hindsight. I like the terse F# syntax I ended up with. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment