Skip to content

Instantly share code, notes, and snippets.

@dansimpson
Created January 27, 2021 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dansimpson/5d49439d0f5cfe1f73a3f0fc80ccdf9b to your computer and use it in GitHub Desktop.
Save dansimpson/5d49439d0f5cfe1f73a3f0fc80ccdf9b to your computer and use it in GitHub Desktop.
class ResultError < Exception; end
abstract class Result(V, E)
abstract def unwrap : V
abstract def error : E
abstract def ok? : Bool
abstract def error? : Bool
abstract def and_then(&block : V -> Result(V, E)) : Result(V, E)
abstract def or_else(&block : E -> Result(V, E)) : Result(V, E)
abstract def if_present(&block : V -> Void) : Result(V, E)
abstract def map(&block : V -> U) : Result(U, E) forall U
class Ok(V, E) < Result(V, E)
protected def initialize(@value : V)
end
def unwrap : V
@value
end
def error : E
raise ResultError.new("Ok has no error")
end
def ok? : Bool
true
end
def error? : Bool
false
end
def and_then(&block : V -> Result(U, E)) : Result(U, E) forall U
yield unwrap
end
def or_else(&block : E -> Void) : self
self
end
def if_present(&block : V -> Void) : self
yield unwrap
self
end
def map(&block : V -> U) : Result(U, E) forall U
Result(U, E).ok(yield unwrap)
end
def log!
Log.info { "Ok: #{unwrap}" }
end
end
class Error(V, E) < Result(V, E)
protected def initialize(@error : E)
end
def error : E
@error
end
def unwrap : V
raise ResultError.new("Error has no value")
end
def ok? : Bool
false
end
def error? : Bool
true
end
def if_present(&block : V -> Void) : self
self
end
def and_then(&block : V -> Result(U, E)) : Result(U, E) forall U
Result(U, E).error(error)
end
def or_else(&block : E -> Void) : self
yield error
self
end
def map(&block : V -> U) : Result(U, E) forall U
Result(U, E).error(error)
end
def log!
Log.error { "Error: #{unwrap}" }
end
end
def self.ok(value : V) : self
Ok(V, E).new(value)
end
def self.error(error : E) : self
Error(V, E).new(error)
end
end
alias StringResult = Result(String, Exception)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment