Skip to content

Instantly share code, notes, and snippets.

@cherryramatisdev
Created October 21, 2023 04:46
Show Gist options
  • Save cherryramatisdev/657ae9efffb1fe5b916a2859af75e969 to your computer and use it in GitHub Desktop.
Save cherryramatisdev/657ae9efffb1fe5b916a2859af75e969 to your computer and use it in GitHub Desktop.
A simple result monad implemented with type safety using sorbet
# frozen_string_literal: true
# typed: true
require 'sorbet-runtime'
# Result...
module Result
extend T::Sig
# Ok...
class Ok < T::Struct
extend T::Generic
OkVal = type_member
prop :_tag, String, default: 'Ok'
prop :value, OkVal
end
# Err...
class Err < T::Struct
extend T::Generic
ErrVal = type_member
prop :_tag, String, default: 'Err'
prop :value, ErrVal
end
end
# Test...
module Test
extend T::Sig
sig { params(blau: String).returns(T.any(Result::Ok[String], Result::Err[Integer])) }
def self.do_something(blau)
return Result::Err.new(value: 'deu bosta') if blau == 'error'
Result::Ok.new(value: blau)
end
end
my_stuff = Test.do_something('another')
puts my_stuff
case my_stuff
in Result::Ok
puts "OK Value is: #{my_stuff.value}"
in Result::Err
puts "Error Value is: #{my_stuff.value}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment