2012-02-29 96 views
13

這兩個函數有區別嗎?Haskell:(+1)和( x-> x + 1)有什麼區別?

ghct說:

Prelude> :t (+1) 
(+1) :: Num a => a -> a 
Prelude> :t \x->x+1 
\x->x+1 :: Num a => a -> a 

但是

當我使用(1)的語法在這段代碼:

data B = B { 
    pos :: Int, 
    cells :: [Int] 
} deriving (Show) 

createB :: Int -> B 
createB n = B 0 (take n $ repeat 0) 

size :: B -> Int 
size b = length $ cells b 

get_curr :: B -> Int 
get_curr b = (cells b) !! (pos b) 

apply :: (Int -> Int) -> B -> B 
apply f b = let n = pos b 
       h = take n $ cells b  -- head 
       t = drop (n + 1) $ cells b -- tail 
       in B n $ h ++ [f (get_curr b)] ++ t 

-- ... 
eval :: [Char] -> StateT B IO() 
eval [] = return() 
eval (x:xs) = do 
       b <- get 

       put $ case x of 
         '+'   -> apply (+1) b 
         '-'   -> apply (-1) b 
         '>'   -> fwd b 
         '<'   -> back b 
         otherwise -> b 
       -- ... 

前奏(以及編譯器),所述:

> :load BrainFuck.hs 
[1 of 1] Compiling BrainFuck  (BrainFuck.hs, interpreted) 

BrainFuck.hs:49:40: 
    No instance for (Num (Int -> Int)) 
     arising from the literal `1' 
    Possible fix: add an instance declaration for (Num (Int -> Int)) 
    In the expression: 1 
    In the first argument of `apply', namely `(- 1)' 
    In the expression: apply (- 1) b 
Failed, modules loaded: none. 

我在做什麼錯? 對不起,如果代碼是不那麼酷(完整源在這裏:https://github.com/nskeip/bf/blob/a755b2d27292593d63fe1e63c2a6e01cebc73520/BrainFuck.hs

回答

22

此代碼:

(-1) 

...並不意味着同樣的事情,因爲這代碼:

\ x -> x - 1 

-是在Haskell特殊情況;它是該語言中唯一的前綴運算符。當你寫(-1)時,你會得到一個「負數」,而不是「減一個」,這是一個函數。

你應該使用subtract 1來得到你所需要的。

+4

您也可以使用'pred',但請注意'predminBound'會拋出一個異常,而'subtract 1 minBound'將環繞。 – hammar 2012-02-29 18:42:50

11

你的問題不在於(+1),它與(-1)

Prelude> :t (-1) 
(-1) :: Num a => a 

-1 is a number!試着用apply (\x -> x-1) bapply (subtract 1) b

+0

該死! )))) – 2012-02-29 18:16:18

+0

因爲你不需要*一個/前綴'+',所以沒有。 – delnan 2012-02-29 18:19:07

+0

請參閱「中綴運算符的部分」的鏈接 – Joni 2012-02-29 18:19:12

4

(+1)\x -> x + 1之間沒有區別,如果仔細觀察,(+1)不是導致您的錯誤的原因。 (-1)是。這是因爲不像(+1)(-1)不是運營商部分,它是負值。

4

而不是subtract減量表達式也可以直接寫爲(+(-1))

相關問題