“ DoSomething String”的实例声明非法

时间:2019-02-22 07:53:50

标签: haskell

我有以下代码,无法编译:

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"

并且编译器显示以下错误消息:

 :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.  

我在做什么错了?

1 个答案:

答案 0 :(得分:3)

String被定义为type String = [Char],即它是类型的同义词。基本语言禁止为类型同义词编写类实例。您可以将其写为instance DoSomething [Char]或以其他方式打开TypeSynonymInstances语言扩展,并在文件顶部添加{—# LANGUAGE TypeSynonymInstances #-},以编译现有代码,如错误消息所示。

请注意,语言扩展名位于文件顶部,而不位于模块声明下方。