这个“过滤”是否有效?功能存在吗?对于这样的函数,什么名字比较好呢?
我正在解决一个欧拉计划问题,该问题涉及具有特定属性的所有 n 位数字。似乎获取它们的最简单方法可能是获取具有该属性的所有数字的列表(这将是无限长的),然后选择具有正确位数的数字。像这样:
numsWithCoolProperty = filter hasCoolProperty [1..]
nDigitNumsWithCoolProperty n = takeWhile (< 10^n) $ dropWhile (<= 10^(n-1)) numsWithOtherCoolProperty
但现在如果我想用不同的属性做同样的事情,我会重复自己:
nDigitNumsWithOtherCoolProperty n = takeWhile (< 10^n) $ dropWhile (<= 10^(n-1)) numsWithOtherCoolProperty
所以我想要一个捕获 dropWhile/takeWhile 逻辑的函数。类似这样:
f :: (a -> Bool) -> [a] -> [a]
f pred = takeWhile pred . dropWhile (not . pred)
然后如果我有一个谓词 hasNDigits n m
如果 m 有 n 位数字则返回 true,我可以这样做:
nDigitNumsWithCoolProperty n = f (hasNDigits n) numsWithCoolProperty
nDigitNumsWithOtherCoolProperty n = f (hasNDigits n) numsWithOtherCoolProperty
无论如何,我的问题是关于函数 f
它有与 dropWhile 和 takeWhile 相同的类型:它是否已经存在于某处?如果不是的话,取什么名字比较好呢?我能想到的就是像 dropUntilTakeWhile
这样的东西,但我确信有一个更好的名字。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的函数:
与
span
和break
函数密切相关,如您所见:让我们看一些示例:
以及您的函数:
现在,我们有一个与
相关的定律>span
到takeWhile
和dropWhile
,因此我们可能会将您的函数视为
span
和的一部分>break
函数组。它还与词法分析有关,您可以在词法分析中收集一些与谓词匹配的标记。因此,您可以将此函数称为
gather
或lex
或类似的名称。Your function:
Is strongly related to the
span
andbreak
functions, as you can see:Let's see some examples:
and your function:
Now, we have one law relating
span
totakeWhile
anddropWhile
,so we might consider your function part of the
span
andbreak
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
orlex
or something similar.