Recursion or list comprehension?
Working through Learn You a Haskell For Great Good, in the chapter on higher-order functions the author walks through an implementation of a few different library functions. When coming to t开发者_运维技巧he definition of filter'
(a reimplementation of the standard library function filter
), I thought that the obvious thing was this:
filter' f xs = [x | x <- xs, f x]
But the author gives the following longer, recursive definition:
filter' _ [] = []
filter' p (x:xs)
| p x = x : filter' p xs
| otherwise = filter' p xs
Both definitions do the same thing. Is there any reason for this? Is the recursive definition somehow more performant? Is it more idiomatic for Haskell? Something else?
It's probably because the list comprehension is just syntactic sugar, which in principle is translated to the recursive form.
If the authors point is to illustrate how the function is implemented, using a list comprehension shortcut doesn't really do that - it shows an alternative way to express the solution, but not really a functional implementation.
In short, it's showing how to implement from a fairly minimal set of basic building blocks.
This is a guess, though - I haven't read that tutorial myself.
List comprehension is pretty much sugar for a map and a filter in one operation; Although it may use concatMap in the backend. Generally using something of higher abstraction to implement something of lower abstraction is cheating.
精彩评论