Complete adder in haskell

Haskell newbie here. I need help writing a function for a full adder. I have the following:

xor :: Bool -> Bool -> Bool
xor True False = True
xor False True = True
xor _ _ = False

fulladder :: Bool -> Bool -> Bool ->(Bool, Bool)
fulladder a b c =  c xor (a xor b) ++ (a&&b) || ((a xor b) && c)      

      

and I am getting the following error:

  * Couldn't match expected type `(Bool -> Bool -> Bool)
                                    -> Bool -> Bool'
                  with actual type `Bool'
  * The function `a' is applied to two arguments,
      but its type `Bool' has none
      In the first argument of `(&&)', namely `(a xor b)'
      In the second argument of `(||)', namely `((a xor b) && c)'

      

+3


source to share


1 answer


The return type of your function is a tuple . Really:

fulladder :: Bool -> Bool -> Bool -> (Bool, Bool)
--                                   ^ 2-tuple
      

Now (++) :: [a] -> [a] -> [a]

merges lists . So it definitely won't work for building a tuple. So, the first error we resolve is:

fulladder :: Bool -> Bool -> Bool ->(Bool, Bool)
fulladder a b c =  ( c xor (a xor b) , (a&&b) || ((a xor b) && c) )
--                 ^ tuple syntax    ^                            ^ 
      

Later in Haskell, you specify a function followed by arguments. So c xor a

it won't work. You have to use xor c a

(or use backtics). Therefore, we must rewrite it to:

fulladder :: Bool -> Bool -> Bool ->(Bool, Bool)
fulladder a b c =  ( xor c (xor a b) , (a&&b) || ((xor a b) && c) )
--                   ^      ^ right order          ^
      



or alternatively:

fulladder :: Bool -> Bool -> Bool ->(Bool, Bool)
fulladder a b c =  ( c `xor` (a `xor` b) , (a&&b) || ((a `xor` b) && c) )
--                     ^   ^    ^   ^ backtics           ^   ^
      

The function now generates:

*Main> fulladder False False False
(False,False)
*Main> fulladder False False True
(True,False)
*Main> fulladder False True False
(True,False)
*Main> fulladder False True True
(False,True)
*Main> fulladder True False False
(True,False)
*Main> fulladder True False True
(False,True)
*Main> fulladder True True False
(False,True)
*Main> fulladder True True True
(True,True)

      

What is the correct result for outputting and wrapping a tuple.

+7


source







All Articles