Skip to content

Instantly share code, notes, and snippets.

@austintaylor
Created January 10, 2012 21:57
Show Gist options
  • Save austintaylor/1591452 to your computer and use it in GitHub Desktop.
Save austintaylor/1591452 to your computer and use it in GitHub Desktop.
Needing the `Either a` monad in Ruby
loadStuff :: Map -> Either String (ThingOne, ThingTwo)
loadStuff params = do
thingOne <- loadThingOne params
thingTwo <- loadThingTwo params thingOne
checkSomething thingTwo
return (thingOne, thingTwo)
def load_stuff(params)
thing_one, error = load_thing_one(params)
return [nil, nil, error] unless thing_one
thing_two, error = load_thing_two(params, thing_one)
return [nil, nil, error] unless thing_two
error = check_something(thing_two)
return [nil, nil, error] if error
[thing_one, thing_two, nil]
end
@austintaylor
Copy link
Author

I think this is the best way to do this in Ruby. There was a bunch of duplicated error/success handling code (modify session, redirect, etc), which needed to be extracted so that the loading part could be reused. A more imperative solution would be to push the outcome code down into methods, and then override those methods (the inheritance approach) or to move them into a delegate (the Objective-C approach).

@pzol
Copy link

pzol commented May 1, 2012

You might find this Either monad useful https://github.com/pzol/monadic#either

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment