2011-04-07 51 views
1

有人可以用簡單的話是什麼這兩個運營商做給我解釋一下:

$ 

\ 
+0

反斜槓是在特定上下文中具有特殊含義的符號。 '$'是[前奏](http://hackage.haskell.org/packages/archive/base/latest/doc/html/src/GHC-Base.html#%24)中定義的函數。 – 2011-04-07 21:06:22

+0

另請參閱http://stackoverflow.com/questions/2787543/haskell-what-is-the-difference-between-dollar-and-dollar-exclamation-poi – 2011-04-24 19:36:02

回答

15

\不是運算符,它是字面語法的一部分。更準確地說,它是兩個字面語法的一部分:它表示一個lambda字面值,它用作字符串文字中的轉義字符。

操作$在前奏定義爲

($) :: (a -> b) -> a -> b 
f $ x = f x 

換句話說,它恰好同樣的事情不空白,即只是簡單的功能的應用程序。 但是,雖然函數應用程序是左關聯的並且具有高優先級(實際上最高),但$是右關聯的並且具有低優先級。

這可以讓你當你有像「f應用於g應用於h應用於x」,這不$運營商將這樣寫

f (g (h x)) 

,但與運營商可以鏈省略括號寫成

f $ g $ h x 

如果要將函數應用程序運算符本身作爲參數傳遞給另一個函數,它也很有用。假設您有函數列表和值列表,並且您希望將列表中的每個函數應用到另一個列表中的相應值:

zipWith ($) fs xs 
2

($)::(A - > B) - > a - > b base Prelude,base Data.Function Application operator。這個操作符是多餘的,因爲普通的應用程序(f x)的含義與(f $ x)相同。但是,$具有較低的右聯合綁定優先級,因此它有時會允許省略括號;

關鍵字\ 反斜槓 「\」 在多行字符串被用來>在lambda函數爲 「foo \> \欄」>>> \ X - > X + 1

7

什麼這兩個運營商做: $ \

第一個,($),是運營商,其定義爲:

-- | Application operator. This operator is redundant, since ordinary 
-- application @(f x)@ means the same as @(f '$' x)@. However, '$' has 
-- low, right-associative binding precedence, so it sometimes allows 
-- parentheses to be omitted; for example: 
-- 
-- >  f $ g $ h x = f (g (h x)) 
-- 
-- It is also useful in higher-order situations, such as @'map' ('$' 0) [email protected], 
-- or @'Data.List.zipWith' ('$') fs [email protected] 

($)      :: (a -> b) -> a -> b 
f $ x     = f x 

它可以讓你用更少的parenthesese寫入功能。

第二個標記\lambda abstractions的匿名函數的Haskell語法的一部分。

因此,例如

\x -> x + 1 

是一個將其參數加1的函數。 lambda抽象的語法是described in the Haskell Report