Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Number to String Word Representation

Tags:

haskell

I'm doing a mini exercise to help me out with a much larger one. For now, I am trying to write a function called "digitStr" that has the signature of (I think) digitStr :: String -> String.

What I'm trying to do here is that when I type something like the following, I should get the following output:

> digitStr "23"
"twenty three"

For now, assume that numbers only go up to 25.

WHAT I'VE TRIED ON MY OWN:

My first idea was to add numerical words into the database.

wrdtxt :: txt
wrdtxt = " one"," two"," three"," four"," five","six"," seven"," eight"," nine"," ten"," eleven"," twelve","thirteen"," fourteen","fifteen"," sixteen"," seventeen"," eighteen"," nineteen", " twenty"

The next step is to make a function that takes a string and outputs it into a list of strings:

numWords :: String -> [String]
numWords "" = []
numWords x = words x

The next step is to take the length of the function. If its length is 2, we look at the 1st digit to determine if it's in the 10s or 20s. If it is "25", somehow, do "twenty" ++ "five".

As you can tell, I am a bit confused on what to do. I've been thinking about this for the past 2 days and this is all I can come up with.

like image 898
The Hound Avatar asked May 05 '26 10:05

The Hound


1 Answers

Here's how to pattern match Strings:

numWords :: String -> [String]
numWords []  =  ...    -- matches only the empty string
numWords [a] =  ...    -- matches when argument is just  a single char;
                          a = the digit
numWords [a,b] = ...   -- matches when there are exactly two chars;
                          a = first chars, b = second char
numWords ['1',b] = ... -- matches when there are exactly two characters and
                          the first char is '1'; b is set to the second char
numWords (a:as) = ...  -- matches when there is at least one character;
                          a = first character, as = second through last characters

But you might also want to consider changing the signature of numWords to take an Int:

numWords :: Int -> [String]
numWords x
  | x < 10  = ...     -- x is a single digit
  | x < 20  = ...     -- x is between 11 and 19
  | x < 30  = ...     -- x is between 20 and 29
  | ...
like image 100
ErikR Avatar answered May 08 '26 13:05

ErikR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!