Reputation: 22460
I am trying to extract the value in the Right
constructor of a Either
value, while giving an error if the Either
in question is actually a Left
(i.e. an error). The answers in Either Right Left how to read value gives me something like:
fromRight e = either (const $ error "Either Left encountered while expecting Right") id e
This works but discards useful information in the error message of the Left
ctor of Either
. How can I post an error message about the Left
instead?
-- EDIT --
Thanks for the input. I wanted this as a more informational version of fromJust
.
Also, I'd like to avoid writing a case
statement every time, and want to avoid Monads whenever it's not too complicated (to keep the function "eval" style). For my use case, it's computation-oriented, and errors occur only when something like invalid input was supplied (when there is no remedy).
I ended up using:
fromRight e = either (error.show) id e
Upvotes: 0
Views: 925
Reputation: 48581
Instead of using const ...
in the first argument of either
, use something else.
either oops .... where
oops x = error $ "Oops! Got an " ++ show x
Or whatever.
Note, however, that error
should only be used for internal errors. User errors, connectivity errors, etc., should be allowed to bubble out to IO
and then reported with throwIO
or handled gracefully.
Upvotes: 4
Reputation: 94289
Instead of
const $ error "Left encountered"
you can use a lambda to get the value and use it, e.g.
\v -> error $ "Left encountered: " ++ v
Upvotes: 3