Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from Either?

Tags:

haskell

I have this code in ghci,try to decode base64 code:

let a=pack "MTExMTEx"
let b=decode a
:t b
b :: Either String ByteString

so how to get the decode bytestring from either?is there some func like Maybe's fromJust?I can't find it,thanks.

like image 500
wang kai Avatar asked Oct 26 '17 01:10

wang kai


3 Answers

Use case:

case decode a of
  Left err -> {- what to do if decode gave an error -}
  Right msg -> {- what to do if decode succeeded -}

The either function that Alexandre suggests is essentially the same as this, the two branches are just taken as functions instead; i.e. it's equivalent to write:

either 
  (\err -> {- what to do if decode gave an error -}) 
  (\msg -> {- what to do if decode succeeded -}) 
  (decode a)
like image 161
luqui Avatar answered Nov 13 '22 02:11

luqui


You can use the either function from Data.Either.

Its signature is:

either :: (a -> c) -> (b -> c) -> Either a b -> c

It means it takes two functions as inputs: the first one to be applied in case it's a Left, and the second one to be applied if it's a Right. The third parameter is your Either data type. Notice that the type of the return value of both functions must be the same.

like image 36
Alexandre Lucchesi Avatar answered Nov 13 '22 02:11

Alexandre Lucchesi


You're looking for Data.Either's fromRight which has a type signature

fromRight :: b -> Either a b -> b

the first value is a default value (what you'll get back if you have a Left instead of a Right.

fromRight 'a' (Left "b")
-- gives 'a'

fromRight 'a' (Right 'c')
-- gives 'c'
like image 43
Adam Smith Avatar answered Nov 13 '22 02:11

Adam Smith