2016-07-15 127 views
2

我有這兩個表達式:

  1. foldr (-) 0 . map (uncurry (*)) $ coords 5 7

  2. foldr (-) 0 . map (uncurry (*)) (coords 5 7)

的(1)作品打印出來的結果,但(2)有錯誤說:

<interactive>:50:15: 
    Couldn't match expected type ‘a -> t0 c’ 
       with actual type ‘[Integer]’ 
    Relevant bindings include 
     it :: a -> c (bound at <interactive>:50:1) 
    Possible cause: ‘map’ is applied to too many arguments 
    In the second argument of ‘(.)’, namely 
     ‘map (uncurry (*)) (coords 5 7)’ 
    In the expression: foldr (-) 0 . map (uncurry (*)) (coords 5 7) 

任何人都可以告訴我這兩者有什麼區別?謝謝。

回答

3

這裏有一個簡單的例子:

Prelude> id . id $ "Example" 
"Example" 
Prelude> id . id ("Example") 
<interactive>:2:10: 
    Couldn't match expected type ‘a -> c’ with actual type ‘[Char]’ 
    Relevant bindings include it :: a -> c (bound at <interactive>:2:1) 
    In the first argument of ‘id’, namely ‘("Example")’ 
    In the second argument of ‘(.)’, namely ‘id ("Example")’ 
    In the expression: id . id ("Example") 

的問題是功能應用的優先級比(.)強。的($)修復了這個固定性級別:

id . id $ "Example" = (id . id) $ "Example" 
        = (id . id) "Example" 

然而,隨着(...),功能應用勝你最終使用(.)與非功能第二個參數:

id . id ("Example") = id . id "Example" 
        = id . (id "Example") -- apply id 
        = id . ("Example") 
        = type error, since "Example" isn't a function 
+0

我現在看到,謝謝,我想知道爲什麼(uncurry(*)))作爲參數與()不會導致問題,但最後一個參數(座標5 7)呢?和順便說一句,如果表達式中有多個$?口譯員會如何解釋這個表達? – linjunshi

3
foldr (-) 0 . map (uncurry (*)) $ coords 5 7 
-- is equivalent to 
(foldr (-) 0 . map (uncurry (*))) (coords 5 7) 
-- and to 
foldr (-) 0 (map (uncurry (*)) (coords 5 7)) 


foldr (-) 0 . map (uncurry (*)) (coords 5 7) 
-- is equivalent to 
foldr (-) 0 . (map (uncurry (*)) (coords 5 7)) 
-- and to 
\x -> foldr (-) 0 (map (uncurry (*)) (coords 5 7) x) 

在後者中,map (uncurry (*)) (coords 5 7)的結果傳遞給.作爲第二個參數,但它是一個列表,而不是一個函數,所以類型的錯誤出現。

需要注意的是還行:

foldr (-) 0 $ map (uncurry (*)) (coords 5 7) 
2

$是一個簡單的中綴形式沒有操作。因爲它的中綴運算符具有低固定性:

GHCi> :i $ 
($) :: (a -> b) -> a -> b -- Defined in ‘GHC.Base’ 
infixr 0 $ 

它在其中出現的任何表達被解析彷彿它有括號。在你的榜樣,

foldr (-) 0 . map (uncurry (*)) $ coords 5 7 

被解析爲

( (foldr (-) 0) 
    . (map (uncurry (*)))) 
$ (coords 5 7) 

因爲$.低固定性。這與您編寫1 + 2 * 3的方式完全相同:解析爲(1) + (2*3),因爲*+具有更高的固定性。

$運營商則評估,它是所有應用的LHS的功能 - 在你的情況下,這是foldr (-) 0 . map (uncurry (*)) - 在RHS表達coords 5 7。將函數應用於其參數當然也正是如果您只寫了function (argument),但是您需要指定正確的函數!要編寫例如沒有$,你必須組作爲

(foldr (-) 0 . map (uncurry (*))) (coords 5 7) 

,而你嘗試不同的分析:功能應用結合更加緊密地比任何綴,甚至.,所以你的努力就等於

foldr (-) 0 . (map (uncurry (*)) (coords 5 7)) 

這是沒有道理的。

相關問題