[Haskell-cafe] How to improve below code?

Andy Stewart lazycat.manatee at gmail.com
Tue Jun 9 09:59:58 EDT 2009


Hi all,

I have below source code, i use Dynamic for `pageBuffer`.
In implement of function `pageClone`, after `case pt of`, i need write 
like this, and this code looks ugly, if `PageTyep` have 100 type, i need
write those ugly code 100 times.

            case pt of
              TStringBuffer -> pageBufferClone (x :: StringBuffer)
              TImageBuffer  -> pageBufferClone (x :: ImageBuffer)
              TVideoBuffer  -> pageBufferClone (x :: TVideoBuffer)
              TMixBuffer    -> pageBufferClone (x :: TMixBuffer)
              
So have a better solution to avoid write above ugly code?

Someone suggestion me use GADTs instead, but i don't know how to write correct
GADTs code replace current version, if GADTs is best way, someone can
explain it detail? It's better if someone give me demo code.

------------------------------> Source Code start <------------------------------
data PageType = TStringBuffer | TImageBuffer | TVideoBuffer | TMixBuffer
             deriving (Eq, Show, Read)

data Page =
    Page {pageName      :: IORef String
         ,pageId        :: Int
         ,pageType      :: PageType
         ,pageBuffer    :: Dynamic
         ,pageBox       :: VBox
         }

class PageBuffer a where
    pageBufferClone :: a -> IO (Dynamic, VBox)

-- | Page clone interface.
pageClone :: Page -> IO Page
pageClone page = do
  -- Get common information for clone page.
  name <- pageGetName page
  let id = pageId page
      pt = pageType page
      pb = pageBuffer page

  -- Get clone information for dynamic interface. 
  (pBuffer, pBox) <- 
      case fromDynamic pb of
        Just x -> 
            case pt of
              TStringBuffer -> pageBufferClone (x :: StringBuffer)
              TImageBuffer  -> pageBufferClone (x :: ImageBuffer)
              TVideoBuffer  -> pageBufferClone (x :: TVideoBuffer)
              TMixBuffer    -> pageBufferClone (x :: TMixBuffer)
        Nothing -> pageCloneEmpty

  -- Return clone page.
  pageNewInternal name id pt pBuffer pBox
------------------------------> Source Code end   <------------------------------

Thanks!

  -- Andy




More information about the Haskell-Cafe mailing list