Skip to content

Instantly share code, notes, and snippets.

@phimuemue
Created September 4, 2011 12:15
Show Gist options
  • Save phimuemue/1192779 to your computer and use it in GitHub Desktop.
Save phimuemue/1192779 to your computer and use it in GitHub Desktop.
encode tuples into numbers
import Data.List
import Maybe
-- taken from
-- http://www.haskell.org/haskellwiki/Prime_numbers_miscellaneous#Prime_Wheels
primes = 2:3:primes'
where
l:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]
primes' = p : filter isPrime candidates
isPrime n = all (not . divides n)
$ takeWhile (\p -> p*p <= n) primes'
divides n p = n `mod` p == 0
isPrime n = all not [n `mod` p == 0 | p <- takeWhile (\p -> p*p <= n) primes]
ascendlist [] = []
ascendlist (h:t) = h : (ascendlist (map (+ h) t))
deascendlist [] = []
deascendlist (h:t) = h : map (flip (-) h) (deascendlist t)
encode l = encode' (ascendlist l) where
encode' [] = 1
encode' (h:t) = (primes !! (fromIntegral h)) * (encode' t)
getsprime n = if isPrime n then n else fromJust (find (\x -> n `mod` x == 0) primes)
decode n = deascendlist (decode' n) where
decode' 1 = []
decode' n = (fromIntegral pi) : (decode' (n `div` p)) where
p = getsprime n
pi = fromJust (findIndex (== p) primes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment