Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding constructor

Tags:

module

haskell

I'm a beginner in Haskell. Let's say Rat is the type of fractions of integeres or an integer. I'd like to ask, why does export this the Rat's constructors?

module RatNum(Rat,add1Rat,makeRat) where
    infixl 5 :/
    data Rat = Int :/ Int | Only Int deriving(Show)
    add1Rat :: Rat -> Rat
    add1Rat (a :/ b) = (a+b) :/ b
    add1Rat (Only a) = Only (a+1)
    makeRat :: Rat
    makeRat = 1 :/ 1
    makeORat :: Rat
    makeORat = Only 1

In GHCI:

Prelude> :l RatNum
[1 of 1] Compiling RatNum           ( RatNum.hs, interpreted )
Ok, modules loaded: RatNum.
*RatNum> Only 5
Only 5
*RatNum> add1Rat (1:/3)
4 :/ 3
*RatNum> 7:/5
7 :/ 5

The module is not finished yet and I'd like to hide the constructors of Rat.

like image 645
drumath Avatar asked Sep 06 '12 12:09

drumath


1 Answers

It's because you're loading the module itself from ghci. Try out this code, in a file Main.hs in the same directory as RatNum.hs:

module Main where

import RatNum

f = Only 1

Now try to load Main from ghci:

$ ghci Main.hs
GHCi, version 7.0.4: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 2] Compiling RatNum           ( RatNum.hs, interpreted )
[2 of 2] Compiling Main             ( Main.hs, interpreted )

Main.hs:5:5: Not in scope: data constructor `Only'
Failed, modules loaded: RatNum.

EXPLANATION

Have a look at this ghci manual page, section 2.4.5. It explains that every module GHCI puts into your command prompt is currently in scope; the visible identifiers are exactly those that would be visible in a Haskell source file with no import declaration (cite).

Your command prompt says RatNum because you told ghci to load it, so the prompt works in the same scope as within that module. In my example it was only referenced by the module I actually loaded, Main, thus I did not enter in the scope of RatNum.

When you will actually compile (or reference through imports) your code, the export declarations will work as you expect.

like image 61
Riccardo T. Avatar answered Oct 19 '22 08:10

Riccardo T.