[Haskell-cafe] Re: Function to cast types

Achim Schneider barsoap at web.de
Sun Mar 22 09:39:33 EDT 2009


Anonymous Anonymous <temp.public at gmail.com> wrote:

> Hello,
> 
> I'm new to haskell, I'm wondering how can you write a function that
> will do the following:
> 
> fromIntToString :: Int -> String
> 
> this is a cast function to cast an Int to a String. I know such
> function exist, however let's assume it didn't exist. How would I
> write such function? 
>
I have no Idea, but this one works:

intOfChar c | c >= '0' && c <= '9' = fromEnum c - fromEnum '0'
intOfChar _ = undefined

intOfString = sum . map (uncurry (*)) . zip (map (10^) [0..]) 
            . map intOfChar . reverse

...assuming that 0..9 are consecutive in the Char Enum, which they are.

Reading intOfString backwards, you get: reverse the string, change each
digit to its integer value, pair it up with the right power of 10,
multiply those pairs, and finally sum everything up.

You can replace map f . zip with zipWith f , but that doesn't change
much.

-- 
(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