Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string contains a certain character

Tags:

haskell

I need to check if my string contain a specific character.

I tried this:

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

But it gives me:

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

I know that filter:

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

How could I reach the goal and return a bool instead of a list?

like image 732
PlayHardGoPro Avatar asked Aug 23 '15 12:08

PlayHardGoPro


2 Answers

For your purpose, you could use the function elem :: Eq a => a -> [a] -> Bool from prelude. It does exactly what it says on the label. To implement this function, I would use something like this:

elem = any . (==)

or even more elementary:

elem x = foldr ((||) . (x ==)) False

Notice that due to the short-circuit behaviour of (||) this also works with infinite lists as long as x is found.

like image 101
fuz Avatar answered Oct 14 '22 06:10

fuz


The type of filter is (a -> Bool) -> [a] -> [a].

You have supplied the first argument which has type Char -> Bool (which is correct), then the second argument which is String (that's [Char]) which is correct, so the type of filter (\x -> x == c) s is [Char].

But the type signature you have provided says the function returns a Bool, which doesn't match the actual type returned.

You probably want to use any instead of filter. It's type is (a -> Bool) -> [a] -> Bool.


There's also an all function that returns True if and only if all elements of the list satisfy the predicate passed. You may also consider the functions or and and that given a [Bool] compute the disjunction or conjunction of the values. So any f = or . map f and all f = and . map f.

For all list-related functions see the Data.List module.

like image 7
Bakuriu Avatar answered Oct 14 '22 07:10

Bakuriu