Why can I not make String an instance of a typeclass?

前端 未结 4 722
甜味超标
甜味超标 2020-12-12 16:05

Given:

data Foo =
  FooString String
  …

class Fooable a where --(is this a good way to name this?)
  toFoo :: a -> Foo
<
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-12 16:29

    FlexibleInstances are not a good answer in most cases. Better alternatives are wrapping the String in a newtype or introduce a helper class like so:

    class Element a where
       listToFoo :: [a] -> Foo
    
    instance Element Char where
       listToFoo = FooString
    
    instance Element a => Fooable [a] where
       toFoo = listToFoo
    

    See also: http://www.haskell.org/haskellwiki/List_instance

提交回复
热议问题