2017-05-03 53 views
3

Haskell新手在这里。我需要一些帮助,为全加器编写一个函数。 我有以下几点:Haskell的全加器

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)  

,我发现了以下错误:

* 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)' 
+0

但是你的函数不返回两个元素? –

+0

我认为你可能正在寻找'\'xor \''(使其成为中缀所需的反引号)。因为现在你正在对'xor'和'b'这两个参数应用'a'。 – ryachza

+2

您目前实现了一个完整的功能,然后尝试调试它失败的原因。如果你从小处开始建设,你可以让自己变得更容易。例如,'fulladder a b c = True ++ True'可能是一个很好的第一个虚拟实现:它失败了,但它更短,更容易查找。一旦你解决了这个问题,你可以扩展到'ful = bc =(True xor True,True)',等等,直到你完全表达。 –

回答

7

你的函数的返回值类型是元组。事实上:

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

现在(++) :: [a] -> [a] -> [a]会连接名单。所以这绝对不会构建一个元组。所以我们解决的第一个错误是:

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

接下来在Haskell中,指定一个函数,后面跟随参数。所以c xor a将无法​​正常工作。你应该使用xor c a(或使用backtics)。所以,我们应该把它改写为:

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

或者:

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

现在函数生成:

*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) 

这对输出携带正确的结果元组。