[Haskell-cafe] Either example

mukesh tiwari mukeshtiwari.iiitm at gmail.com
Thu Feb 7 19:05:07 CET 2013


Hi Jocob
I would recommend you to go through the LYH (
http://learnyouahaskell.com/making-our-own-types-and-typeclasses ) .
data Either a b = Left a | Right b deriving (Eq, Ord, Read, Show)

Lets say you have a division function and you want to avoid division by
zero so this simple function
simpleDiv :: Int -> Int -> Int
simpleDiv m n = div m n

will through error and stop executing rest of you code ( See more on error
handling ) so you can write your function which can handle this

division :: Int -> Int -> Either String Int
division m n
   | n == 0 = Left "Division by zero"
   | otherwise = Right  $ div m n

You can extend this solution as you wish and lets say you want both , some
times integer division and some times floating point division based on
flag. You set you flag true for floating division and false for integer
division.

data Either' a b c = Left a | Mid b | Right c  deriving ( Show , Eq )

tempFunction :: Int -> Int -> Bool -> EIther' String Double Int
tempFunction m n f
   | n == 0 = Left "Division by zero"
   | f = Mid $ m / n
   | otherwise = Right $ div m n


I haven't tested this code but the idea is if you want to return different
results then you use this. Also see Use of Either (
http://book.realworldhaskell.org/read/error-handling.html  ). Hopefully I
have explained it correctly.

--Mukesh

On Thu, Feb 7, 2013 at 8:07 AM, Jacob Thomas <jthomas7 at ucsc.edu> wrote:

>
> Hello
>
> I'm new to Haskell, and need help with figuring out the Either type...
> Any example to show how this works?
>
> Jacob
>
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20130207/9b2e9839/attachment.htm>


More information about the Haskell-Cafe mailing list