在Haskell中,为什么我必须在这段代码中使用美元符号? [英] In Haskell, why do i have to use the dollar sign in this code?
问题描述
import Data.Char
groupsOf _ [] = []
groupsOf n xs =
取n xs:groupsOf n(尾部xs)
problem_8 x =最大值。地图产品。 groupsOf 5 $ x
main = do t< - readFilep8.log
let digits = map digitToInt $ concat $ lines t
print $ problem_8 digits
在 problem_8 x =最大值。地图产品。 groupsOf 5 $ x
为什么不能只是groupsOf 5 x?
是因为x以后会扩展到其他表达式(这里是: digits = map digitToInt $ concat $ lines t
)?这就是所谓的懒惰(x现在不会扩展,但也许以后)?
没有 $
,优先顺序如下所示:
最大值。地图产品。 (groupsOf 5 x)
自。
(函数组合)以两个函数作为参数,并且 groupsOf 5 x
不能返回函数,这是一个错误。
使用 $
,优先顺序如下所示:
(最大。地图产品。groupsOf 5)x
这相当于(通过函数组合) p>
最大值(地图产品(groupsOf 5 x))
$ b
或者:
pre $ $ $ $ $ $ $ $ $ $ $ $ $ / code>
(然而,像 $
这样的字符串被认为是糟糕的样式)
这与懒惰无关,请注意。
I'm still trying to crack this code:
import Data.Char
groupsOf _ [] = []
groupsOf n xs =
take n xs : groupsOf n ( tail xs )
problem_8 x = maximum . map product . groupsOf 5 $ x
main = do t <- readFile "p8.log"
let digits = map digitToInt $concat $ lines t
print $ problem_8 digits
In problem_8 x = maximum . map product . groupsOf 5 $ x
why can't it just be groupsOf 5 x ?
is it because x will later be expanded to some other expressions(here it will be: digits = map digitToInt $concat $ lines t
) ? is this the so-called lazy(x wont be expanded now, but maybe later) ?
Without the $
, the precedence works out like this:
maximum . map product . (groupsOf 5 x)
Since .
(function composition) takes two functions as arguments, and groupsOf 5 x
cannot return a function, this is an error.
With the $
, the precedence works out like this:
(maximum . map product . groupsOf 5) x
This is equivalent (via function composition) to:
maximum (map product (groupsOf 5 x))
or:
maximum $ map product $ groupsOf 5 x
(however stringing along $
like this is considered poor style)
This has nothing to do with laziness, note.
这篇关于在Haskell中,为什么我必须在这段代码中使用美元符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!