gpt4 book ai didi

haskell - Haskell 中对 ($) 的混淆 : example where ($) does not plainly substitute parentheses

转载 作者:行者123 更新时间:2023-12-02 14:49:34 25 4
gpt4 key购买 nike

假设我有数据类型

data Price = Price Double
data Book = Book {title :: String, bookPrice :: Price}

使用提取数字价格的函数

priceAsDouble :: Price -> Double
priceAsDouble (Price doubleValue) = doubleValue

现在,我想编写一个累加器来折叠书籍列表,例如

go :: Double -> Book -> Double
go acc book = acc + priceAsDouble (bookPrice book)

这很好并且可以编译。

但是,如果我将最后一行更改为

go acc book = acc + priceAsDouble $ bookPrice book

我收到以下相互矛盾的编译器错误:

<interactive>:10:51:
Couldn't match expected type ‘Price -> Double’
with actual type ‘Double’
The first argument of ($) takes one argument,
but its type ‘Double’ has none
In the expression: acc + priceAsDouble $ bookPrice book
In an equation for ‘go’:
go acc book = acc + priceAsDouble $ bookPrice book

<interactive>:10:57:
Couldn't match expected type ‘Double’
with actual type ‘Price -> Double’
Probable cause: ‘priceAsDouble’ is applied to too few arguments
In the second argument of ‘(+)’, namely ‘priceAsDouble’
In the expression: acc + priceAsDouble

问题:我认为 ($) 只不过是括号 () 的语法糖。显然,我错了。我的想法哪里错了?

最佳答案

$ 括号的语法糖,但它不适用于您期望的级别。

go acc book = acc + priceAsDouble $ bookPrice book

实际上被解释为

go acc book = (acc + priceAsDouble) (bookPrice book)

但是 acc + PriceAsDouble 作为 GHC 的函数没有意义。

讽刺的是,你需要更多的括号才能使其工作:

go acc book = acc + (priceAsDouble $ bookPrice book)

关于haskell - Haskell 中对 ($) 的混淆 : example where ($) does not plainly substitute parentheses,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32550691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com