[Haskell-cafe] Re: Function to cast types

Achim Schneider barsoap at web.de
Sun Mar 22 10:00:54 EDT 2009


Achim Schneider <barsoap at web.de> wrote:

> Anonymous Anonymous <temp.public at gmail.com> wrote:
> 
> > fromIntToString :: Int -> String
> > 
> intOfString = sum . map (uncurry (*)) . zip (map (10^) [0..]) 
>             . map intOfChar . reverse
> 
/me hides under a stone and tries again, this time with the correct
problem:

import Data.List

charOfInt :: Int -> Char
charOfInt c | c >= 0 && c <= 9 = toEnum (c + fromEnum '0')
charOfInt _ = undefined

stringOfInt :: Int -> String
stringOfInt =
    let f (-1) = Nothing
        f n = let (r,c) = n `divMod` 10
              in Just $ if r == 0 then (c, (-1)) else (c, r)
    in map charOfInt . reverse . unfoldr f

That -1 thing is clearly inelegant, but I don't feel like struggling
with off-by-one errors, right now. Negative numbers are left as an
exercise.

-- 
(c) this sig last receiving data processing entity. Inspect headers
for copyright history. All rights reserved. Copying, hiring, renting,
performance and/or quoting of this signature prohibited.




More information about the Haskell-Cafe mailing list