2014-02-24 42 views
1

我目前正在學習Haskell與99 questions和我在一個解決方案中看到.。這似乎是在數學知通常的功能組成:爲什麼在Haskell中需要花括號爲'neg square 4.2'?

f ∘ g 

我想確保我的理解正確無誤,並創造了這個例子:

square x = x*x 
neg x = (-1)*x 

main = do 
    -- let result = neg (square 4.1) -- works 
    -- let result = square (neg 4.2) -- works 
    -- let result = neg $ square 4.3 -- works 
    let result = neg square 4.4 -- doesn't work 
    -- let result = neg . square 4.5 -- doesn't work 
    -- let result = neg . square $ 4.6 -- works 
    -- let result = neg square $ 4.7 -- does not work 

    print result 

可悲的是,只有前三行工作(至少他們按預期工作)。

爲什麼我需要在較低2案件括號?我以爲你不會需要他們,becasue我認爲用點,neg得到square作爲輸入。所以它仍然是一個函數,看起來像

(-1)*x*(-1)*x 

然後4.4擺在那裏了x這應該是罰款。

我認爲沒有點,Haskell首先應用square到4.5,然後neg應用於結果。

但顯然是有問題的。下面兩種情況下的問題是什麼?

+0

由於'infixr'指定了'.','$'(以及函數應用暗示)的優先級,'neg。平方4.5 ==(。)(neg)(square 4.5)','neg。方$ 4.6 ==($)((。)(NEG)(平方))(4.6)'和'負方$ 4.7 ==($)(NEG(廣場))(4.7)' –

回答

0

類型的neg

neg:: Num a => a -> a 

您正在嘗試應用兩個參數NEG時只需要一個。 (.)是函數的組合物,而不是串聯。

let result = neg . square 4.5應該let result = neg . square $ 4.5

在您正在撰寫兩個函數的neg . square情況。

類型的(.)(b -> c) -> (a -> c) -> a -> c 所以,當你與negsquare變得neg . square :: Num c => c -> c,現在有一個參數合成它。如果您嘗試立即應用到42neg . square4.4應用於square應用將優先應用於4.4(因爲函數應用是左聯)的negsquare的組成和會產生一個錯誤類型。

6

功能的應用程序()在哈斯克爾所有運營商的優先級最高,所以

neg . square 4.5意味着neg . (square 4.5),這沒有任何意義,因爲(square 4.5)是一個數字,而不是一個功能,所以你不能用neg撰寫。

neg square $ 4.7意味着(neg square) $ 4.7,但square是一個函數不是一個數字,所以你不能neg它。

相關問題