$(美元)和 $! 有什么区别?(美元感叹号) [英] What is the difference between $ (dollar) and $! (dollar exclamation point)

查看:102
本文介绍了$(美元)和 $! 有什么区别?(美元感叹号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释 Haskell 运算符 ($)($!)(美元符号与美元符号感叹号)之间的区别?

Can anybody explain the difference in Haskell between the operators ($) and ($!) (dollar sign vs dollar sign exclamation point)?

到目前为止,我还没有在任何地方看到 $! 的使用,但是在浏览 Haskell reference,我注意到它的存在,并且它的定义与 $ 完全相同.在 Haskell 解释器 (GHCi) 中尝试一些简单的语句时,我找不到任何区别,在搜索 haskell 教程 时,我也无法在最上面列出的教程中找到对运算符的任何参考.

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.

这与 Haskell 中的普通惰性函数应用相反,例如fxf $ x,它们首先开始计算函数 f,并且只计算参数 x 如果需要.

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.

例如 succ (1 + 2) 将通过创建一个 thunk 来延迟添加 1 + 2,并首先开始评估 succ.仅当需要 succ 的参数时,才会对 1 + 2 求值.

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.

但是,如果您确定始终需要函数的参数,则可以使用 ($!),它将首先将参数评估为弱头范式,然后进入函数.这样,您就不会创建一大堆 thunk,这会更有效率.在这个例子中,succ $!1 + 2会先计算3,然后输入函数succ.

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!

这篇关于$(美元)和 $! 有什么区别?(美元感叹号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆