Either type in repl

What is the best way to extract a Right/Left value in repl without having to write functions that do it every time?
This is ugly:

a = Right 3
getRight x = head $ rights [x]
getRight a -- 3

edit: fromRight requires providing an alternative value, but it may not be trivial to create one with complicated types.

1 Like

As a one-off, you can write this (pattern matching, or what the imperative programmers call “destructuring assignment”):

ghci> foo = Right 5
ghci> let Right x = foo in x
5

As for getRight, I would define it similarly using pattern matching:

getRight (Right x) = x

Of course, using such things in real-world code is strongly advised against, but no harm no foul in the repl. :slight_smile:

3 Likes

You can even do:

ghci> foo = Right 5
ghci> let Right x = foo
ghci> x
5

That way you can use x multiple times.

5 Likes

You don’t even need to use let:

ghci> foo = Right 5
ghci> Right x = foo
ghci> x
5
4 Likes

Old habit, I guess!

I was curious about when the requirement to use let was removed, and I managed to find the ticket (I think). Apparently it was removed in 8.0.1!

3 Likes

Use fromRight undefined? Or the either or extra libraries: Either a b -> a - Hoogle.

2 Likes