I have written the following code to remove vowels from a sentence:
main = print $ unixname "The House"
vowel x = elem x "aeiouAEIOU"
unixname :: [Char] -> [Char]
unixname [] = []
unixname (x:xs) | vowel x = unixname xs
| otherwise = x : unixname xs
Just wondering if it is possible to create a data type for vowel? The compiler won’t let me use characters in a data type.
Not directly. The problem is that characters are a built-in type with no facility for polymorphism. This is different from numeric literals, which are designed to be polymorphic via the
Numtype class.That said, there are two basic approaches you can take: a newtype wrapper with a smart constructor, or a totally new type.
The newtype wrapper is easier to use:
Since the
Vowelconstructor isn’t exported, newVowels can only be created by thevowelfunction, which only admits the characters you want.You could also make a new type like this:
This second way is pretty heavyweight, and therefore is much more awkward to use.
So that’s how to do it. I’m not quite certain that you want to though. The usual idiom is to make types that represent your data, and you specifically don’t represent vowels. A common pattern would be something like this:
Here the newtype differentiates between unsanitized and sanitized input. If the only way to make a
CleanStringis bycleanString, then you know statically that everyCleanStringis properly sanitized (provided thatcleanStringis correct). In your case, it seems you actually need a type for consonants, not vowels.Newtypes in Haskell are very lightweight*, but the programmer does have to write and use code to do the wrapping and unwrapping. In many instances the benefits outweigh the extra work. However, I really can’t think of any application where it’s important to know that your
Stringis vowel-free, so I’d probably just work with a plainString.*newtypes only exist at compile-time, so in theory there’s no runtime performance cost to using them. However, their existence can change the produced code (e.g. inhibiting RULEs), so sometimes there is a measurable performance impact.