Haskell: 关于部分应用的问题

Haskell: Question about Partial Application

我正在阅读 Miran Lipovaca 的书 'Learn You a Haskell for Great Good!' 并在第 5 章学习高阶函数。

其中一个示例涉及以下函数:

applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)

以下是函数输出的示例:

ghci> applyTwice (++ " HAHA") "HEY"
"HEY HAHA HAHA"

ghci> applyTwice ("HAHA " ++) "HEY"
"HAHA HAHA HEY"

对于第一个示例,我了解到该字符串是按以下方式使用连接运算符生成的:

"HEY" ++ " HAHA"
"HEY HAHA" ++ " HAHA"
"HEY HAHA HAHA"

但是,我不明白第二个示例中的串联运算符是如何工作的。输出字符串 "HAHA HAHA HEY" 是如何产生的?任何见解表示赞赏。

For the first example, I understand that the string was produced by using the concatenation operator in the following manner:

"HEY" ++ " HAHA"
"HEY HAHA" ++ " HAHA"
"HEY HAHA HAHA"

与其直接跳转到中缀表达式(即 ++ 介于两者之间),不如从函数的角度考虑会有所帮助。

(++ " HAHA") :: [Char] -> [Char]   -- #1 this is a function (++ is partially applied)     
"HEY" :: [Char]

(++ " HAHA") "HEY"                 -- apply "HEY" as an argument to #1
-- same as "HEY" ++ " HAHA"

(+) :: (Num a) => a -> a -> a      -- #2 a binary function
(+) 1 2                            -- #3 apply 1 and 2 as arguments to #2
-- same as 1 + 2

-- technically, #3 is curried as
--    ((+) 1) 2                    -- i.e. (+) 1 is a partially applied function, which is then applied to 2     

如果将 (++ " HAHA") 代入 applyTwice 的定义中,您将得到

applyTwice f x = f (f x)
applyTwice (++ " HAHA") "HEY" = (++ " HAHA") ((++ " HAHA") "HEY")

                              = (++ " HAHA") ("HEY" ++ " HAHA")
                              = (++ " HAHA") ("HEY HAHA")
                              = "HEY HAHA" ++ " HAHA"
                              = "HEY HAHA HAHA"

现在对 applyTwice ("HAHA " ++) "HEY" 做同样的事情。

applyTwice f x = f (f x)
applyTwice ("HAHA " ++) "HEY" = ("HAHA " ++) (("HAHA " ++) "HEY")

                              = ("HAHA " ++) ("HAHA " ++ "HEY")
                              = ("HAHA " ++) ("HAHA HEY")
                              = "HAHA " ++ "HAHA HEY"
                              = "HAHA HAHA HEY"