【发布时间】:2014-02-19 08:14:00
【问题描述】:
是的,另一个美元符号问题。对不起... (我用了搜索功能!)
我的函数式编程课程教授告诉我们,美元符号 '有点添加一个左括号,然后在末尾添加一个右括号'(它以或多或少相同的方式非常粗略地描述了here)。所以
fibs = 0 : 1 : zipWith (+) fibs $ tail fibs
应该等价于
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
好吧,事实并非如此。第二件事编译正常,第一件事报错:
jkjj.hs:1:8:
Couldn't match expected type `[a1] -> [a1]' with actual type `[a0]'
The first argument of ($) takes one argument,
but its type `[a0]' has none
In the expression: 0 : 1 : zipWith (+) fibs $ tail fibs
In an equation for `fibs':
fibs = 0 : 1 : zipWith (+) fibs $ tail fibs
fibonacci.hs:1:16:
Couldn't match expected type `[a0]' with actual type `[a1] -> [a1]'
In the return type of a call of `zipWith'
Probable cause: `zipWith' is applied to too few arguments
In the second argument of `(:)', namely `zipWith (+) fibs'
In the second argument of `(:)', namely `1 : zipWith (+) fibs'
当然,因为 $ 是一个函数,所以像:
fibs = 0 : 1 $ zipWith (+) fibs (tail fibs)
行不通,所以至少我的教授给出的解释过于简单化了。在写这篇文章时,我尝试放置括号,以便错误是相同的。我得到了:
fibs = (0 : 1 : zipWith (+) fibs) $ tail fibs
和
fibs = (0 : 1 : zipWith (+) fibs) (tail fibs)
它们都给了我完全相同的错误消息(当然,除了列号)。为什么是这样? a b $ c d 是否等价于 (a b) (c d) 而不是 a b (c d)?我认为这一切都与函数优先级和/或关联性有关,但我不知道具体细节。我不知道你怎么能看到一个函数的优先级(除了尝试很多组合),我也不能用谷歌找到它。
希望有人能帮我解决这个问题!
【问题讨论】:
-
好吧,在您引用的 FP 文章中,它显示 A $ 被解释为:接下来是您正在调用的函数的最后一个参数。,所以问题是,我正在调用的函数是什么?显然,正如您所发现的那样,表达式从 $ 离开。
-
真的!但 zipWith 似乎是“你正在调用的函数”的更明显的选择。
标签: haskell dollar-sign