haskell - 检查字符串是否包含某个字符

标签 haskell

我需要检查我的字符串是否包含特定字符。

我试过这个:

charFound :: Char -> String -> Bool
charFound c s = filter(\x -> x == c) s

但它给了我:

Couldn't match expected type Bool with actual type [Char]



我知道那个过滤器:

returns a list constructed from members of a list (the second argument) fulfilling a condition given by the first argument.



我怎样才能达到目标并返回一个 bool 值而不是一个列表?

最佳答案

为了您的目的,您可以使用函数 elem :: Eq a => a -> [a] -> Bool从前奏。它完全符合标签上的要求。为了实现这个功能,我会使用这样的东西:

elem = any . (==)

甚至更基本的:
elem x = foldr ((||) . (x ==)) False

请注意,由于 (||) 的短路行为只要 x,这也适用于无限列表被发现。

关于haskell - 检查字符串是否包含某个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32166754/

相关文章:

haskell - 如何读取目录中的所有文件名?

haskell - Haskell中的同构 `fmap`

haskell - 以这种方式定义构图有什么问题?

haskell - 如果我尝试运行简单的 binTree,GHCi 就会卡住

haskell - 将 Data.Constraint.Forall 与等式约束一起使用

Haskell:为什么 ((.).(.)) f g 等于 f 。克x?

haskell - 为什么 Hoogle 和 :t? 显示的 Text.Parsec.Token.natural 类型不同

haskell - haskell中的双 map ?

haskell - Haskell 中是否会发生堆栈溢出错误?

haskell - 如何从Haskell矩阵中的某个位置提取值?