Skip to content

Instantly share code, notes, and snippets.

@darkf darkf/PrimeEnc.hs
Last active Sep 7, 2016

Embed
What would you like to do?
Baseless number encoder
import Data.Numbers.Primes (primes, primeFactors)
import Data.List (elemIndex)
import Control.Monad (forM_)
data N = P N | Z | Prod [N] deriving (Eq, Show)
primes' = 1 : primes
primeIndex n = let Just idx = elemIndex n primes' in idx
encode :: Int -> N
encode 0 = Z
encode 1 = P Z
encode n = Prod $ map (P . encode . primeIndex) $ primeFactors n
decode :: N -> Int
decode Z = 0
decode (P n) = primes' !! decode n
decode (Prod ns) = product $ map decode ns
main = forM_ [0..2^32-1] $ \n -> encode n `seq` return ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.