有多少个参数需要Haskell的foldr函数? [英] How many arguments takes the foldr function of Haskell?
问题描述
我是新来的Haskell,我读的书真世界哈斯克尔。在本书的第4章中,作者要求使用fold来重写groupBy函数。这本书的读者之一(Octavian Voicu)给出了以下解决方案:
theCoolGroupBy ::(a - >一 - >布尔) - >并[a] - > [[α]]
theCoolGroupBy当量XS =尾$ foldr相似步骤(\_ - > [[]])XS $(\_ - >假)
其中step x acc = \ p - > if px then rest p else []:rest(eq x)
where rest q = let y:ys = acc q in(x:y) :ys
我的问题很简单:我知道foldr需要3个参数:一个函数,一个初始值和一个列表。但是在代码的第二行中,foldr需要4个参数。 为什么发生这种情况?
谢谢。
Scott的答案是正确的, foldr
是一个函数,所以这就是为什么看起来 foldr
需要4个参数。 foldr
函数确实需要3个参数(函数,基数,列表):
*主> :type foldr
foldr ::(a - > b - > b) - > b - > [a] - > b
我会在这里举一个简单的例子:
inc :: Int - > (Int→Int)
inc v = \ x - > x + v
test = inc 2 40 - 测试输出为42
在上面的代码中, inc
接受一个参数, v
,并返回一个函数, code> v 。
如下所示, inc 2 $
* Main> :type inc
inc :: Int - > Int - > Int
* Main> :type inc 2
inc 2 :: Int - > Int
* Main> :type inc 2 40
inc 2 40 :: Int
圆括号可以用来强调返回值是一个函数,但在功能上与上面的代码相同:
* Main> (inc 2)40
42
PS:我是原评论的作者:)
I am new to Haskell and I am reading the book "Real World Haskell". In the Chapter 4 of the book the author asks as an exercise to rewrite the groupBy function using fold. One of the readers of the book (Octavian Voicu ) gave the following solution:
theCoolGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
theCoolGroupBy eq xs = tail $ foldr step (\_ -> [[]]) xs $ (\_ -> False)
where step x acc = \p -> if p x then rest p else []:rest (eq x)
where rest q = let y:ys = acc q in (x:y):ys
My question is simple: I know that foldr takes 3 arguments: a function, an initial value and a list. But in the second line of the code foldr takes 4 arguments. Why this happens? Thank you.
Scott's answer is correct, the result of the foldr
is a function, so this is why it seems that foldr
takes 4 arguments. The foldr
functions does take 3 arguments (function, base, list):
*Main> :type foldr
foldr :: (a -> b -> b) -> b -> [a] -> b
I'll just give here an example that is less complex:
inc :: Int -> (Int -> Int)
inc v = \x -> x + v
test = inc 2 40 -- output of test is 42
In the above code, inc
takes one argument, v
, and returns a function that increments its argument by v
.
As we can see below, the return type of inc 2
is a function, so its argument can simply be added at the end:
*Main> :type inc
inc :: Int -> Int -> Int
*Main> :type inc 2
inc 2 :: Int -> Int
*Main> :type inc 2 40
inc 2 40 :: Int
Parentheses could be used to emphasize that the return value is a function, but functionally it is identical to the above code:
*Main> (inc 2) 40
42
PS: I'm the author of the original comment :)
这篇关于有多少个参数需要Haskell的foldr函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!