User Tools

Site Tools


codesnippets:fnowarnorphans

{-# OPTIONS_GHC -fno-warn-orphans #-}

  • prevents warnings of orphan instance, meaning:
    • instance declaration of a type is not declared in the module of the class
  • NOTE: Orphan instances may be useful.
  • NOTE: The purpose of the examples here is only to demonstrate the impact on the compiler. The examples may not make sense as a use case of type classes.
  • example:
    • code of module Lib:
      module Lib
          (
              MyClass(..)
          ) where
       
      class Num x => MyClass x where
          fMy :: x -> x
    • code of module Main:
      import Lib (MyClass(..))
       
      main :: IO ()
      main = print x1
       
      instance MyClass Double where
          fMy x = (x * x) + x + 1
       
      x1 :: Double
      x1 = fMy 3.4 
    • compiler warning, when using -Wall:
      app\Main.hs:6:1: warning: [-Worphans]
          Orphan instance: instance MyClass Double
          To avoid this
              move the instance declaration to the module of the class or of the type, or
              wrap the type with a newtype and declare the instance on the new type.
        |
      6 | instance MyClass Double where
        | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...
  • example, with GHC option:
    • code:
      {-# OPTIONS_GHC -fno-warn-orphans #-}
       
      import Lib (MyClass(..))
       
      main :: IO ()
      main = print x1
       
      instance MyClass Double where
          fMy x = (x * x) + x + 1
       
      x1 :: Double
      x1 = fMy 3.4 
    • compiles, error and warning free, with compiler: GHC 8.10.4, using compiler option -Wall
    • executes, with output:
      15.959999999999999

This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
You could leave a comment if you were logged in.
codesnippets/fnowarnorphans.txt · Last modified: by 127.0.0.1

Except where otherwise noted, content on this wiki is licensed under the following license: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki