簡體   English   中英

如何在Haskell中使用$ operator curry函數應用程序?

[英]How does function application with the $ operator curry in Haskell?

我正在學習haskell並且有點困惑函數應用程序運算符$ curry的。

根據GHC,$的類型是

*Main>:t ($)
($) :: (a->b) -> a -> b

但我可以輸入以下代碼

*Main>map ($ 2) [(*2), (+2), (/2)]
[4.0,4.0,1.0]

根據$的簽名,雖然我認為我需要使用翻轉函數,因為$的第一個參數是(a-> b)。

例如,我不能做以下事情

curry_test :: Integer -> String -> String
curry_test x y = (show x) ++ " " ++ y
*Main> let x = curry_test "123"
    Couldn't match expected type `Integer' with actual type `[Char]'
In the first argument of `curry_test', namely `"123"'
In the expression: curry_test "123"
In an equation for `x': x = curry_test "123"

但我能做到

let x = curry_test 2

中綴運營商有特殊規則。 請參閱此頁: http//www.haskell.org/haskellwiki/Section_of_an_infix_operator

基本上,由於$是一個中綴運算符, ($ 2)實際上將2固定為$的第二個參數,所以它相當於flip ($) 2

這個想法是使操作員的部分應用程序更直觀,因此,例如,如果您在列表上map (/ 2) ,您可以想象將列表的每個元素放在除法符號左側的“缺失”點。

如果你想以這種方式使用curry_test函數,你可以這樣做

let x = (`curry_test` "123")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM