Last active
December 18, 2015 17:29
-
-
Save tmhedberg/5819070 to your computer and use it in GitHub Desktop.
Polymorphic Gray code generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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