-----------------------------------------------------------------------------
-- |
-- Module      :  Data.UDCode
-- Copyright   :  (c) Mark Jason Dominus 2008, Walter George Rorie-Baety 2008
-- License     :  BSD-style (see the file LICENSE)
-- 
-- Maintainer  :  <black DOT meph AT gmail STOP com>
-- Stability   :  experimental
-- Portability :  non-portable (internal ADT-using pattern guards)
--
-- UDCode: a naive Haskell implementation of Mark Jason Dominus'
-- uniquely-decodable code algorhythm, as described in
-- http://blog.plover.com/CS/udcodes.html entry. For more documentation,
-- see the blog entry directly.
--
-----------------------------------------------------------------------------

module Data.UDCode
         ( is_udcode
         , ud_pair  -- Top-level functions
         ) where

import Data.UDCode.Helper(cPairs)
import Data.Foldable(toList)
import Data.List(length, sortBy)
import Data.Maybe(isNothing)
import Data.Ord(comparing)
import Data.Set(fromAscList)

ud_pair      :: Eq a => [[a]] -> Maybe ([[a]], [[a]])
is_udcode    :: Eq a => [[a]] -> Bool

-- | isUDCode is rather direct: if uDPair finds no pair, then it's a UD code,
-- and same for the converse.
is_udcode = isNothing . ud_pair

-- | uDPair is a facade, for a later-mentioned function, cPairs. uDPair ensures
-- that the list cPairs works with is non-empty, ordered from smallest to
-- longest, and has no duplicate members.
ud_pair  []   = Nothing
ud_pair  [_]  = Nothing
ud_pair list  = (cPairs . toList . fromAscList . sortBy (comparing length)) list