Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a number into its digits with Haskell

Tags:

haskell

Given an arbitrary number, how can I process each digit of the number individually?

Edit I've added a basic example of the kind of thing Foo might do.

For example, in C# I might do something like this:

static void Main(string[] args) {     int number = 1234567890;     string numberAsString = number.ToString();      foreach(char x in numberAsString)     {         string y = x.ToString();         int z = int.Parse(y);         Foo(z);     } }  void Foo(int n) {     Console.WriteLine(n*n); } 
like image 915
Greg B Avatar asked Oct 18 '10 20:10

Greg B


People also ask

Does split () work on numbers?

JavaScript split method can be used to split number into array. But split method only splits string, so first you need to convert Number to String. Then you can use the split method with a combination of map method to transform each letter to Number.

How do you split a number into digits in Python?

To split an integer into digits:Use the str() class to convert the integer to a string. Use a list comprehension to iterate over the string. On each iteration, use the int() class to convert each substring to an integer.

What is integral Haskell?

Haskell has two integral types, namely Int and Integer . Int is the type of limited-precision integers; this means that there is a smallest integer of type Int , namely minBound , and a greatest integer of type Int , namely maxBound .


2 Answers

Have you heard of div and mod?

You'll probably want to reverse the list of numbers if you want to treat the most significant digit first. Converting the number into a string is an impaired way of doing things.

135 `div` 10 = 13 135 `mod` 10 = 5 

Generalize into a function:

digs :: Integral x => x -> [x] digs 0 = [] digs x = digs (x `div` 10) ++ [x `mod` 10] 

Or in reverse:

digs :: Integral x => x -> [x] digs 0 = [] digs x = x `mod` 10 : digs (x `div` 10) 

This treats 0 as having no digits. A simple wrapper function can deal with that special case if you want to.

Note that this solution does not work for negative numbers (the input x must be integral, i.e. a whole number).

like image 132
Dave Clarke Avatar answered Oct 03 '22 08:10

Dave Clarke


digits :: Integer -> [Int] digits = map (read . (:[])) . show 

or you can return it into []:

digits :: Integer -> [Int] digits = map (read . return) . show 

or, with Data.Char.digitToInt:

digits :: Integer -> [Int] digits = map digitToInt . show 

the same as Daniel's really, but point free and uses Int, because a digit shouldn't really exceed maxBound :: Int.

like image 30
muhmuhten Avatar answered Oct 03 '22 10:10

muhmuhten