1

I have following code, that does not compile:

module Lib where

{-# LANGUAGE OverloadedStrings, TypeSynonymInstances, FlexibleInstances #-}

import Data.Text (Text)

class DoSomething a where
  something :: a -> IO ()

instance DoSomething String where
  something _ = putStrLn "String"


instance DoSomething Text where
  something _ = putStrLn "Text"

and compiler shows following error message:

 :l ./src/Lib.hs
[1 of 1] Compiling Lib              ( src/Lib.hs, interpreted )

src/Lib.hs:10:10: error:
    • Illegal instance declaration for ‘DoSomething String’
        (All instance types must be of the form (T t1 ... tn)
         where T is not a synonym.
         Use TypeSynonymInstances if you want to disable this.)
    • In the instance declaration for ‘DoSomething String’
   |
10 | instance DoSomething String where
   |          ^^^^^^^^^^^^^^^^^^
Failed, no modules loaded.  

What am I doing wrong?

softshipper
  • 32,463
  • 51
  • 192
  • 400

1 Answers1

3

String is defined as type String = [Char], I.e. it is a type synonym. The base language forbids writing class instances for type synonyms. You can either write this as instance DoSomething [Char] or otherwise turn on the TypeSynonymInstances language extension with a {—# LANGUAGE TypeSynonymInstances #-} at the top of your file to make your existing code compile, as the error message suggests.

Note that language extensions go on top of the file, not below the module declaration.

Cubic
  • 14,902
  • 5
  • 47
  • 92
  • 4
    The OP has already done this (or tried to) - it appears the real problem is that the pragmas are in the wrong place. You do mention this in your final paragraph, but I think it's better to be explicit. – Robin Zigmond Feb 22 '19 at 08:26
  • IIRC, `FlexibleInstances` implies `TypeSynonymInstances`. – dfeuer Feb 22 '19 at 09:52