[英]Haskell - How to write (.) f f = (\x -> f (f x))
I need to write on a module to be run on GHCi, with a function composition to the same function. 我需要在GHCi上运行一个模块,并将函数组合到同一个函数中。 This (The classic fog(x) = f(g(x))
) runs: 这(经典fog(x) = f(g(x))
)运行:
(.) f g = (\x -> f (g x)).
The problem appears when I try to write it like this 当我尝试像这样写它时出现问题
(.) f f = (\x -> f (f x)). (fof(x) = f(f(x)))
GHCi says: GHCi说:
"Conflicting definitions for `f'
Bound at: Lab1.hs:27:9
Lab1.hs:27:12"
Line 27:9 appear on the first time f and line 27:12 appear f again. 第27:9行出现在第一次f,行27:12再次出现f。
Why doesn't Haskell understand (.) ff = (\\x -> f (fx))
? 为什么Haskell不理解(.) ff = (\\x -> f (fx))
?
As the error message says, you have conflicting definitions for f
in the definition (.) ff = (\\x -> f (fx))
. 正如错误消息所示,您在定义(.) ff = (\\x -> f (fx))
对f
的定义存在冲突。 You are binding the name f
to both the first and second arguments to (.)
, so ghci
doesn't know which argument to use when evaluating the expression fx
. 您将名称f
绑定到(.)
的第一个和第二个参数,因此ghci
在计算表达式fx
时不知道要使用哪个参数。
There is nothing wrong with defining (.)
using the pattern (.) fg
, and then calling it with two arguments that happen to be the same. 定义(.)
使用模式(.) fg
,然后用两个恰好相同的参数调用它没有错。
In Haskell, arguments to a function must have unique names. 在Haskell中,函数的参数必须具有唯一的名称。 Using the same name for another argument is not allowed. 不允许对另一个参数使用相同的名称。 This is because 这是因为
foo x y = ... === foo = (\x-> (\y-> ...))
and if y
where replaced with x
, the second x
would just shadow the first inside the ...
body: there would be no way to reference the first x
from there. 如果y
替换为x
,则第二个x
只会遮挡...
body中的第一个:没有办法从那里引用第一个x
。
You can just define twice fx = f (fx)
: 你可以定义twice fx = f (fx)
:
Prelude> :t twice 前奏>:t两次
twice :: (t -> t) -> t -> t 两次::(t - > t) - > t - > t
Prelude> twice (+1) 4 前奏>两次(+1)4
6 6
Alternatively, f (fx) = (.) ffx = join (.) fx
: 或者, f (fx) = (.) ffx = join (.) fx
:
Prelude Control.Monad> :t join (.) Prelude Control.Monad>:t join(。)
join (.) :: (b -> b) -> b -> b join(。)::(b - > b) - > b - > b
join
is defined in Control.Monad
. join
在Control.Monad
定义。 For functions, it holds that join gx = gxx
. 对于函数,它认为join gx = gxx
。 It is also known as W combinator . 它也被称为W组合器 。
Eg print $ join (.) (+1) 4
prints 6 . 例如, print $ join (.) (+1) 4
打印6 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.