I was again playing around with Haskell to learn it a bit better. I do not
found a function to turn a String into an Integer
This is what I come up with:
string_to_int_list :: String -> [Int]
-- filter out all Digits first and then turn it into a list
-- of integers
string_to_int_list = filter (\ch -> isDigit ch) .| map (\ch -> digitToInt ch)
int_list_to_integer:: [Int] -> Integer
int_list_to_integer li = to_integer 0 li
where
to_integer acc [] = acc
to_integer acc (x:xs) = to_integer (acc * 10 + toEnum x) xs
infixl 9 .|
(.|) :: (a -> b) -> (b -> c) -> a -> c
g .| f = f . g
string_to_integer :: String -> Integer
string_to_integer = string_to_int_list .| int_list_to_integer
I guess it's nt all too bad style (comments appriciated)
But it does not work for negative numbers. I guess I can solve this just
isn't there a functions which takes e.g
"-1" and turns that into an Integer?
I do not found it
"-123" it should turn to '[-1,2,3]'
Of course for negative numbers the accumulation would be bad too but that's
another story. So what I want is just function that extract all numbers out
of a String and that's it. I can't believe there isn't some function for
that.
So my question is: Exists such a function or do I have to write it on my own? And the
other is what would you
think would be a good Haskell soluton for turing a string to an Integer.
I'm using HUGS from Feb 2000
Regards
Friedrich