Home > other >  Is there a type that includes strings and lists in haskell?
Is there a type that includes strings and lists in haskell?

Time:01-02

Right now I'm trying to make a basic function that removes any spaces or commas from a sentence.

stringToIntList :: [Char] -> [Char]
stringToIntList inpt = [ a | a <- inpt, a `elem` [" ",","]]

The problem I'm experiencing is that every type I've tried doesn't work, if I put [Char] it freaks out at commas, if I put [string] it freaks out at spaces, and if I put string it just doesn't recognize a and says it's an error. so I was wondering if there was some type that could work as both a [Char] and a [string].

CodePudding user response:

With the current type, the definition needs to be

stringToIntList inpt = [ a | a <- inpt, a `elem` [' ',',']]

(single quotes, because these are Char literals, not String ones!),
or alternatively

stringToIntList inpt = [ a | a <- inpt, a `elem` " ,"]

(using the fact that a string is just a list of characters),
or simply

stringToIntList = filter (`elem` " ,")

Note that this doesn't remove spaces and commas, on the contrary those are the only characters it keeps. To remove them instead, you need to invert the predicate:

stringToIntList = filter $ not . (`elem` " ,")

If you really did want a `elem` [" ",","] then the type of your function would need to be

stringToIntList :: [String] -> [String]

or equivalently [[Char]] -> [[Char]].

  • Related