问题描述
任何人都可以解释运算符($)
和($!)
(美元符号vs美元符号感叹号)?
到目前为止我还没有看到 $!
的使用,但是在浏览Haskell 时,我注意到它的存在,并且它具有与 $ 。在Haskell解释器中尝试一些简单的语句时(),我找不到任何在搜索 haskell tutorial
时,我也无法在顶部列出的教程中找到对运算符的任何参考。
所以,出于好奇,有什么区别,如果有的话?
($! )
是严格的函数应用程序。也就是说,它在评估函数之前评估参数。
这与Haskell中正常的懒惰函数应用相反,例如, 例如 fx
或 f $ x
,它首先开始评估函数 f $ c如果需要的话,只计算参数
x
。
succ(1 + 2)
会通过创建一个thunk来延迟添加 1 + 2
,并开始评估 succ首先
。只有当需要succ的参数时,才会评估 1 + 2
。($!)
,它首先将参数计算为弱头标准形式,然后输入函数。这样,你不会创建一大堆thunk,这可以更有效率。在这个例子中, succ $! 1 + 2
首先计算 3
,然后输入函数 succ
。
请注意,将正常的函数应用程序替换为严格的函数应用程序并不总是安全的。例如:
ghci> const 1(错误noo!)
1
ghci> const 1 $! (错误noo!)
***例外:noo!
Can anybody explain the difference in Haskell between the operators ($)
and ($!)
(dollar sign vs dollar sign exclamation point)?
I haven't seen the use of $!
anywhere so far, but while browsing through the Haskell reference, I noticed its existence and that it has the exact same definition as $
. When trying some simple statements in a Haskell interpreter (GHCi), I couldn't find any difference, nor could I find any reference to the operator in the top listed tutorials when searching for haskell tutorial
.
So, just out of curiosity, what is the difference, if at all?
($!)
is strict function application. That is, it evaluates the argument before evaluating the function.
This is contrary to normal lazy function application in Haskell, e.g. f x
or f $ x
, which first start to evaluate the function f
, and only compute the argument x
if it is needed.
For example succ (1 + 2)
will delay the addition 1 + 2
by creating a thunk, and start to evaluate succ
first. Only if the argument to succ is needed, will 1 + 2
be evaluated.
However, if you know for sure that the argument to a function will always be needed, you can use ($!)
, which will first evaluate the argument to weak head normal form, and then enter the function. This way, you don't create a whole big pile of thunks and this can be more efficient. In this example, succ $! 1 + 2
would first compute 3
and then enter the function succ
.
Note that it is not always safe to just replace normal function application with strict function application. For example:
ghci> const 1 (error "noo!")
1
ghci> const 1 $! (error "noo!")
*** Exception: noo!
这篇关于$(美元)和$美元之间有什么区别? (美元感叹号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!