[aklug] Re: How would you write "rebase" in...

From: Christopher Howard <christopher.howard@frigidcode.com>
Date: Thu Aug 04 2011 - 19:58:38 AKDT

{-
   Sorry for the delay, got distracted with the issue of
   dependent types. I think my solution is the same as
   Darren's, but with a recursive rather than iterative
   approach.
-}

type Base = Int

rebase :: Base -> Int -> String
rebase n d = map (\i -> alph !! i) $ reverse (f n d)
   where f n2 d2 | n2 > 0 && d2 > 0 = f' n2 d2 1
         f' _ d3 _ | d3 == 0 = []
         f' n3 d3 e = let remainder = d3 `mod` (n3 `pow` e)
                        in (remainder `div` n3 `pow` (e-1))
                             : f' n3 (d3-remainder) (e+1)

-- for type safety: integers vs. floats issue
pow :: Int -> Int -> Int
pow _ 0 = 1
pow a 1 = a
pow a b | b > 1 = iterate (*a) a !! (b-1)

alph :: [Char]
alph = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
        , 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'
        , 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T'
        , 'U', 'V', 'W', 'X', 'Y', 'Z', 'Δ', 'Ξ', 'Φ', 'Ψ'
        ]

{-
   Explanation: Employs recursive function with an accumulator.
   Generates list of ints where each element is the value of a
   place. Reverses the list and maps it against a list of
   symbols.

   For simplicity, allowed non-exhaustive pattern matching.
-}

-- 
frigidcode.com
theologia.indicium.us
---------
To unsubscribe, send email to <aklug-request@aklug.org>
with 'unsubscribe' in the message body.
Received on Thu Aug 4 19:58:10 2011

This archive was generated by hypermail 2.1.8 : Thu Aug 04 2011 - 19:58:10 AKDT