Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide helper functions when implementing `instance`

Tags:

haskell

I have data RegEx and I want to implement instance Show a => Show RegEx a. Here's my code:

showAtom :: Show a => RegEx a -> String
showAtom (Lit x) = show x
showAtom r       = "(" ++ (show r) ++ ")"

instance Show a => Show (RegEx a) where
    show (Lit x)   = show [x]
    show (Opt r)   = (showAtom r) ++ "?"
    show (Alt p q) = (showAtom p) ++ "|" ++ (showAtom q)
    show (Seq p q) = (show p) ++ (show q)
    show (Rep r)   = (showAtom r) ++ "*"

The showAtom function is just an implementation detail. Is there any way for me to hide it, such that it is visible only withing the instance definition? Or better yet, make it visible only within show.

like image 601
Paul Manta Avatar asked Dec 26 '22 04:12

Paul Manta


1 Answers

Something like this should work:

instance Show a => Show (RegEx a) where
    show x = show' x
      where
        showAtom :: Show a => RegEx a -> String
        showAtom (Lit x) = show x
        showAtom r       = "(" ++ (show r) ++ ")"

        show' (Lit x)   = show [x]
        show' (Opt r)   = (showAtom r) ++ "?"
        show' (Alt p q) = (showAtom p) ++ "|" ++ (showAtom q)
        show' (Seq p q) = (show p) ++ (show q)
        show' (Rep r)   = (showAtom r) ++ "*"

Alternatively, you can just exclude showAtom from the module's export list.

like image 79
Mikhail Glushenkov Avatar answered Jan 16 '23 13:01

Mikhail Glushenkov