I'm trying to learn how to separate one Integer with many numbers into an [Integer], and I've seen a post about this before where they simply used the modulus 10 operator to find the last/remainder over and over and assigned that number to the beginning of an [Int], but why can't you simply convert the number to a String (which I believe is equal to a [Char]) with the show function, then map the read function to each Char in the [Char] to get integer values in each spot of the [Char] to make an [Integer]?
The code I'm imagining is pretty much just like:
deconstructor :: Integer -> [Integer] //(or trying [Char])
deconstructor n
| n < 0 = map read (show (n * (-1)))
| n == 0 = [read "0"] //(This line works)
| otherwise = map read (show n) //(or in [] or with :: [Integer] on the end)
The error it gives is always something along the lines of:
* Couldn't match type `Char' with `[Char]'
Expected: [String]
Actual: String
Just processing show n compiles fine and gives a String/[Char], and the way I understand map is that it just does the left thing (read in this case) to each index of the array on the right (the thing I'm imagining is a [Char]), so what is it that I'm not quite understanding? Would the String have to be already separated into different [String]s or something?
Yes, you have correctly diagnosed the problem.
The issue is that
readmust operate on aString, not a singleChar. If youread "1234", you are applyingreadto aStringand all is well, but if youmap read "1234", you are applyingreadto('1' :: Char), then('2' :: Char), and so on, and Haskell won't accept this mismatch of types.You can convert each
Charto a one-characterStringeither usingsingletonfromData.Listas part of yourmap:or you can use the function
(:[])in place ofsingleton. This is a "section" that does a cons:operation on each character (for the "head") and the empty list[](for the "tail"). I mention this only because it's pretty common in Haskell code "in the wild", so you'll often see it used:So, the following ought to work:
Note that you don't really need the
n == 0case because it's just a special case of the more general case.