Poriferous
Poriferous

Reputation: 1582

Convert an integer into a list of words

I have an integer n, like 130. What I am tasked to do is separate the integer into digits [1, 3, 0] and then for each digit [1, 3, 0] convert them into a legible format ["one", "three", "zero"]. Here's what I've done so far:

digitToWord :: Int -> String
digitToWord n =
  case n of
    1 -> "one"
    2 -> "two"
    3 -> "three"
    4 -> "four"
    5 -> "five"
    6 -> "six"
    7 -> "seven"
    8 -> "eight"
    9 -> "nine"
    0 -> "zero"

The code above takes an integer and returns its legible equivalent.

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

This code takes a number like 130 and then puts each digit into a list, such that the result would be [1, 3, 0].

What I now have to do is use Haskell to convert [1, 3, 0] into ["one", "three", "zero"]. How do I do this?

Upvotes: 0

Views: 642

Answers (1)

Kapol
Kapol

Reputation: 6463

I modified your code a bit to make it compile on my machine. You didn't post the definition of digitToInt, so I used digitToWord directly (probably the name should be changed, because it's a digit character now).

digitToWord :: Char -> String
digitToWord n =
  case n of
    '1' -> "one"
    '2' -> "two"
    '3' -> "three"
    '4' -> "four"
    '5' -> "five"
    '6' -> "six"
    '7' -> "seven"
    '8' -> "eight"
    '9' -> "nine"
    '0' -> "zero"

digits :: Int -> [String]
digits xs = map digitToWord (show xs)

If you already have a list of Ints, then just use your definition of digitToWord in map digitToWord (digits 130)

Upvotes: 2

Related Questions