简体   繁体   English

Haskell:关于部分应用的问题

[英]Haskell: Question about Partial Application

I am reading the book 'Learn You a Haskell for Great Good!' 我正在阅读“为了大好而学习你的哈斯克尔!”这本书。 by Miran Lipovaca and learning about higher-order functions in Chapter 5. 由Miran Lipovaca撰写并在第5章中学习高阶函数。

One of the examples involves the following function: 其中一个示例涉及以下功能:

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

The following are examples of the function's output: 以下是函数输出的示例:

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

ghci> applyTwice ("HAHA " ++) "HEY"
"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"

However, I don't understand how the concatenation operator works in the second example. 但是,我不明白连接运算符在第二个示例中是如何工作的。 How is the output string "HAHA HAHA HEY" produced? 输出字符串“HAHA HAHA HEY”是如何产生的? Any insights are appreciated. 任何见解都表示赞赏。

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" 

Instead of directly jumping to the infix expression (ie ++ is in between), it helps if you think in terms of functions. 而不是直接跳转到中缀表达式(即++介于其间),如果您根据函数进行思考,它会有所帮助。

(++ " 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     

If you substitute (++ " HAHA") into the definition of applyTwice , you get 如果你将(++ " 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"

Now do the same with applyTwice ("HAHA " ++) "HEY" . 现在使用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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM