[Haskell-cafe] Newbie: generating a truth table

Ketil Malde Ketil.Malde at bccs.uib.no
Tue Feb 6 04:32:17 EST 2007

phiroc at free.fr wrote:
> Ketil,
> thanks for you help.
> Here's the code:
> and2 :: Bool -> Bool -> Bool
> and2 a b = a && b
> loop = [ and2 x y  | x <- [True,False], y <- [True,False] ]
> Now, how do I have Haskell print
> printStrLn("True and True = ") + <result of calling and2 True True>
> printStrLn("True and False = ") + <result of calling and2 True False>
Well, if you keep x and y in the table as well, either as a triple
(x, y, and2 x y) or a nested tuple ((x,y), and2 x y) (which would
let you use the lookup function), you can define a function that
converts such a tuple to the approprate string.  Keep in mind
that Bool has a Show instance, so that e.g. show True => "True",
and use ++ to join two strings.

Then, you can 'map' this function on the table to get a list of strings
corresponding to table rows, and use 'concat' or 'unlines'.  When you
have a result you're happy with, you feed it to putStrLn.


More information about the Haskell-Cafe mailing list