Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Character in String function

Hey I'm a pretty new beginner to Haskell and I am having a small problem.

I want to write a function which checks if a given character is in a given string. Here is my code :

inString :: String -> Char -> Bool 
inString [] _ = False 
inString x c = x == c
inString x:xs c = inString xs c

For me this makes perfect sense as I know that Strings are just Lists of Characters. But I am getting a Parse error in pattern : inString.

Any help would be appreciated.

like image 229
Killerfrid Hd Avatar asked Aug 11 '21 22:08

Killerfrid Hd


Video Answer


1 Answers

You have to think in the types for each expresion:

inString :: String -> Char -> Bool 
inString [] _ = False 
inString (x::String) (c::Char) = x == c -- won't compile char and strings cannot be compared because they have different type
inString (x:xs) c = inString xs c -- add parenthesis to x:xs -> (x:xs)

So a possible way would be:

inString :: String -> Char -> Bool 
inString [] _ = False 
inString (x:xs) c = if x == c then True else inString xs c
like image 196
A Monad is a Monoid Avatar answered Sep 22 '22 12:09

A Monad is a Monoid