[Haskell-cafe] Either example

Harald Bögeholz bo at ct.de
Thu Feb 7 18:33:33 CET 2013


Am 07.02.13 03:37, schrieb Jacob Thomas:
> Hello
> 
> I'm new to Haskell, and need help with figuring out the Either type...
> Any example to show how this works?

Maybe a program I wrote a while ago can help you get it.

https://github.com/ctbo/slitherlink

In Slitherlink.hs there is a function readProblem that can fail. It
returns either a String with an error message (Left) or the problem read
(Right).

[...]
readProblem :: String -> Either String Problem
readProblem s = do
            pl <- readProblemList s
            when (null pl) $ Left "Problem is empty."
            let columns = length $ head pl
            when (columns == 0) $ Left "Problem starts with an empty line."
            unless (all ((== columns) . length) pl) $ Left "Problem not
rectangular."
            let rows = length pl
            return $ listArray ((0, 0), (rows-1, columns-1)) $ concat pl
[...]

Or if you don't feel comfortable with using the Either monad, look at
the even simpler function readConstraint a few lines earlier in the same
file.

In the main solve.hs program this is used to output a meaningful error
message to the user if the input file is invalid:

[...]
  where work s n = case readProblem s of
             Left e -> putStrLn e
             Right p -> do
[...do something with the problem p...]


Hope this helps.

Harald

-- 
Harald Bögeholz    <bo at ct.de> (PGP key available from servers)
Redaktion c't      Tel.: +49 511 5352-300  Fax: +49 511 5352-417
                   http://www.ct.de/

                   int f[9814],b,c=9814,g,i;long a=1e4,d,e,h;
                   main(){for(;b=c,c-=14;i=printf("%04d",e+d/a),e=d%a)
                   while(g=--b*2)d=h*b+a*(i?f[b]:a/5),h=d/--g,f[b]=d%g;}
                                                          (Arndt/Haenel)

                   Affe Apfel Vergaser

/* Heise Zeitschriften Verlag GmbH & Co. KG * Karl-Wiechert-Allee 10 *
   30625 Hannover * Registergericht: Amtsgericht Hannover HRA 26709 *
   Persönlich haftende Gesellschafterin: Heise Zeitschriften Verlag *
   Geschäftsführung GmbH * Registergericht: Amtsgericht Hannover, HRB
   60405 * Geschäftsführer: Ansgar Heise, Dr. Alfons Schräder */



More information about the Haskell-Cafe mailing list