Separate the string and [Char]

I know that String is defined as [Char], but I would like to make the difference between the two of them in an instance of the class. Is this possible with some kind of clever trick besides using newtype to create a separate type? I would like to do something like:

class Something a where doSomething :: a -> a instance Something String where doSomething = id instance (Something a) => Something [a] where doSomething = doSoemthingElse 

And get different results when I call it with doSomething ("a" :: [Char]) and doSomething ("a" :: String) .

I know about FlexibleInstances and OverlappingInstances , but they obviously don't cut the case.

+7
types haskell
source share
3 answers

It's impossible. String and [Char] are the same type. It is impossible to distinguish between two types. With OverlappingInstances you can create separate instances for String and [a] , but [Char] will always use an instance for String .

+11
source share

Why don't you define functions for each case:

 doSomethingString :: String -> String doSomethingString = id doSomethingChars :: (Char -> Char) -> String -> String doSomethingChars f = ... 
+4
source share

As stated earlier, String and [Char] IS are virtually the same.

What you can do is define newtype . It wraps the type (at no cost, since it is completely removed during compilation) and makes it behave like another type.

 newtype Blah = Blah String instance Monoid Blah where mempty = Blah "" mappend (Blah a) (Blah b) = Blah $ a ++ "|" ++ b 
0
source share

All Articles