[英]adding a value with composition and partial application haskell
I'm trying to write this function applying composition and partial application with Haskell: 我正在尝试使用Haskell编写此函数,将其应用到合成和部分应用程序中:
function m n = (m^2) + n
I tried this with: 我尝试使用:
function m = (m^2).(+)
The problem with that approach is that (+)
is a binary operator. 这种方法的问题在于(+)
是二进制运算符。 Since you put it at the right of the dot .
由于您将其放在圆点的右侧.
, it will not be applied to the left operand. ,它将不会应用于左操作数。 So you have written: 所以你写了:
function :: Num a => a -> a -> a
function m = (.) (m^2) (+) -- wrong
This is short for: 这是以下简称:
function m = \n -> ((m^2) ((+) n))
So that means that (+) n
will result in a function (n+)
and we will apply that function to the result of (m^2)
, which does not make much sense. 因此,这意味着(+) n
将产生一个函数(n+)
并且我们将该函数应用于(m^2)
的结果,这没有多大意义。
You can however simply use: 但是,您可以简单地使用:
function :: Num a => a -> a -> a
function m = (+) (m^2)
Or: 要么:
function :: Num a => a -> a -> a
function m = ((m^2) +)
Given function m = (+) (m^2)
, if we apply n
on that function, we will obtain: 给定function m = (+) (m^2)
,如果将n
应用于该函数,则将获得:
((+) (m^2)) n
-> (+) (m^2) n
-> (m^2) + n
You can further modify the function
and drop the m
argument as well, with: 您可以使用以下命令进一步修改该function
并删除m
参数:
function :: Num a => a -> a -> a
function = (+) . (^ 2)
Which is syntactical sugar for: 哪个语法糖适用于:
function :: Num a => a -> a -> a
function = (.) (+) (^2)
If we now apply m
on the function, it will evaluate to: 如果我们现在在函数上应用m
,它将得出:
((.) (+) (^2)) m
-> (\x -> (+) ((^2) x)) m
-> (+) ((^2) m)
-> (+) (m^2)
So we obtain the state like in the previous command. 这样我们就可以像上一条命令一样获得状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.