区分String和[Char]

qwe*_*we2 7 haskell types

我知道String被定义为[Char],但我想在类实例中区分它们.除了使用newtype创建一个单独的类型之外,是否可以使用一些聪明的技巧?我想做的事情如下:

class Something a where     
  doSomething :: a -> a

instance Something String where
  doSomething = id

instance (Something a) => Something [a] where
  doSomething = doSoemthingElse
Run Code Online (Sandbox Code Playgroud)

当我用doSomething ("a" :: [Char])和调用它时得到不同的结果doSomething ("a" :: String).

我知道FlexibleInstances,OverlappingInstances但他们显然不会削减案件.

Dir*_*ple 12

这是不可能的.String并且[Char]是相同的类型.没有办法区分这两种类型.随着OverlappingInstances您可以创建单独的实例String[a],但[Char]总是会使用实例String.

  • 使用newtype.这是std libs给出的方法 (5认同)
  • 更好的是:如果您正在处理文本数据,请使用`Text`数据类型.从这个意义上讲,你可以认为它是一个围绕String的预烘焙新类型包装器,恰好有一个很好的API和更好的性能. (2认同)