开发者

Does this "filtering" function exist? What would be a good name for such a function?

I'm solving a Project Euler problem which involves all the n-digit numbers with a certain property. It seems that the easiest way to get them might be to get a list of all the numbers with that property (which would be infinitely long), then select out the ones with the right number of digits. Like this:

numsWithCoolProperty = filter hasCoolProperty [1..]

nDigitNumsWithCoolProperty n = takeWhile (< 10^n) $ dropWhile (<= 10^(n-1)) numsWithOtherCoolProperty

But now if I want to do the same thing with a different property, I'll be repeating myself:

nDigitNumsWithOtherCoolProperty n = takeWhile (< 10^n) $ dropWhile (<= 10^(n-1)) numsWithOtherCoolProperty

so I want a function that captures the dropWhile/takeWhile logic. Something like:

f :: (a -> Bool) -> [a] -> [a]
f 开发者_JAVA技巧pred = takeWhile pred . dropWhile (not . pred)

and then if I have a predicate hasNDigits n m which returns true if m has n digits, I can do:

nDigitNumsWithCoolProperty n = f (hasNDigits n) numsWithCoolProperty
nDigitNumsWithOtherCoolProperty n = f (hasNDigits n) numsWithOtherCoolProperty

Anyway, my question is about the function f which has the same type as dropWhile and takeWhile: Does it already exist somewhere? If not, what would be a good name for it? All I can think of is something like dropUntilTakeWhile but I'm sure there's a better name out there.


Your function:

f pred = takeWhile pred . dropWhile (not . pred)

Is strongly related to the span and break functions, as you can see:

span  :: (a -> Bool) -> [a] -> ([a], [a]) 

break :: (a -> Bool) -> [a] -> ([a], [a])       

Let's see some examples:

> span (< 3) [1,2,3,4,1,2,3,4]
([1,2],[3,4,1,2,3,4])

> break (< 3) [1,2,3,4,1,2,3,4]
([],[1,2,3,4,1,2,3,4])

and your function:

> f (< 3) [1,2,3,4,1,2,3,4]
[1,2]

Now, we have one law relating span to takeWhile and dropWhile,

span p xs is equivalent to (takeWhile p xs, dropWhile p xs)

so we might consider your function part of the span and break group of functions. It is also related to lexing, where you gather some token that matches a predicate.

So, you might call this function gather or lex or something similar.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜