gpt4 book ai didi

Haskell:关于部分应用的问题

转载 作者:行者123 更新时间:2023-12-02 18:02:01 25 4
gpt4 key购买 nike

我正在读《为大善而学 Haskell!》一书作者:Miran Lipovaca,并在第 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"

关于Haskell:关于部分应用的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56437049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com