[英]How to build this predicate for use with Find?
I want to return a String in a list that contains only Digits. 我想在仅包含数字的列表中返回一个字符串。 I am trying to use the find function to achieve this but am having trouble creating the predicate.
我正在尝试使用find函数来实现这一点,但是在创建谓词时遇到了麻烦。 Here is what I have attempted:
这是我尝试过的:
getYear str | hasYear str = fromJust $ find (map and $ (map.map) isDigit ws) ws
| otherwise = "0"
where ws = words str
I have noticed that my predicate 我注意到我的谓词
map and $ (map.map) isDigit ws
returns a [Bool] with True if one of the Strings contains only digits but isn't designed correctly for use in this instance. 如果其中一个字符串仅包含数字但未正确设计用于此实例,则返回带有True的[Bool]。
There is also the handy 还有方便
all :: (a -> Bool) -> [a] -> Bool
which can be used to write your function 可以用来编写你的函数
find (all isDigit)
弄清楚了:
find (\ws -> and $ map isDigit ws) ws
You can handle that case, when String do not contain the year with fromMaybe
. 当String使用
fromMaybe
不包含年份时,您可以处理这种情况。
getYear = fromMaybe "0" . find (all isDigit) . words
For example, 例如,
λ> fromMaybe "0" . find (all isDigit) $ words "sdf"
"0"
λ> fromMaybe "" . find (all isDigit) $ words "42139 213 f dsf 2"
"42139"
UPD : on the other hand, input String may have some digits, but hasYear
return False
. UPD :另一方面,输入String可能有一些数字,但是
hasYear
返回False
。 That why you shouldn't handle case, when find
returns Nothing
because it will never happened. 这就是为什么您不应该处理情况的原因,当
find
返回Nothing
因为它永远不会发生。
And than your getYear
may looks like that: 而且比您的
getYear
看起来像这样:
getYear str | hasYear str = fromJust . find (all isDigit) . words $ str
| otherwise = "0"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.