user5775230
user5775230

Reputation:

How to properly define a datatype in ghci with Pragma dependency?

I'm trying to define fmap over a Tree type from hammar's answer in Haskell Map for Trees

His definition derives functor, which uses a pragma, which I'm only vaguely familiar with. His definition is

{-# LANGUAGE DeriveFunctor #-}
data Tree a = Leaf a | Node (Tree a) (Tree a)
    deriving (Functor, Show)

I can't get the pragma and definition to work in GHCI. Below are my three mistaken attempts, and I would appreciate any feedback!

First attempt:

Prelude> {-# LANGUAGE DeriveFunctor #-}
Prelude> data Tree a = Leaf a | Node (Tree a) (Tree a)
Prelude>     deriving (Functor, Show)
<interactive>:30:5: parse error on input ‘deriving’

Second try:

Prelude> {-# LANGUAGE DeriveFunctor #-}
Prelude> data Tree a = Leaf a | Node (Tree a) (Tree a) deriving (Functor, Show)
<interactive>:32:57:
    Can't make a derived instance of ‘Functor Tree’:
  You need DeriveFunctor to derive an instance for this class
In the data declaration for ‘Tree’

Third Try:

Prelude> :{
Prelude| {-# LANGUAGE DeriveFunctor #-}
Prelude| data Tree a = Leaf a | Node (Tree a) (Tree a)
Prelude|     deriving (Functor, Show)
Prelude| :}
<interactive>:35:1: parse error on input ‘data’

Upvotes: 3

Views: 193

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477065

In GHCi you set the pragma with :set:

Prelude> :set -XDeriveFunctor

Since the data clause spans over multiple lines, you can declare it between :{ and :}:

Prelude> :{
Prelude| data Tree a = Leaf a | Node (Tree a) (Tree a)
Prelude|     deriving (Functor, Show)
Prelude| :}

now it should work (tested it locally). We can for instance perform an fmap:

Prelude> fmap (+1) (Node (Leaf 12) (Leaf 25))
Node (Leaf 13) (Leaf 26)

Explanation of failed attempts:

  1. the first one fails because your data clause spans over multiple lines, so you should put in on one line, or use some sort of grouping. Nevertheless, you did not enable the pragma, so there are two errors here;
  2. now there is no problem with the data clause, but you can not enable a pragma like this; and
  3. again the pragma is the problem.

Upvotes: 5

Related Questions