Skip to content

Instantly share code, notes, and snippets.

@tmhedberg
Last active December 18, 2015 17:29
Show Gist options
  • Save tmhedberg/5819070 to your computer and use it in GitHub Desktop.
Save tmhedberg/5819070 to your computer and use it in GitHub Desktop.
Polymorphic Gray code generator
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Data.Gray where
import Control.Applicative
class Binary b where zero :: b
one :: b
instance Binary Bool where zero = False
one = True
instance Binary Char where zero = '0'
one = '1'
newtype Bin a = Bin {unBin :: a} deriving Num
instance Num a => Binary (Bin a) where zero = 0
one = 1
grayBits :: (Integral i, Alternative a, Binary b) => i -> a [[b]]
grayBits 1 = pure [[zero], [one]]
grayBits n
| n > 1 =
let grayBits' = grayBits $ n - 1
in
liftA2 (++)
(map (zero:) <$> grayBits')
(map (one:) . reverse <$> grayBits')
| otherwise = empty
grayN :: (Integral i, Alternative a, Binary b) => i -> a [[b]]
grayN n = take (fromIntegral n)
<$> grayBits (ceiling $ logBase 2 $ fromIntegral n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment