String Number to String Word Representation

时间:2015-01-19 23:20:15

标签: haskell

我正在做一个小型练习来帮助我做一个更大的练习。现在,我正在尝试编写一个名为" digitStr"的函数。它具有(我认为)digitStr :: String -> String的签名。

我在这里尝试做的是,当我输入如下内容时,我应该得到以下输出:

> digitStr "23"
"twenty three"

目前,假设数字最多只能达到25个。

我在自己的身上做过什么:

我的第一个想法是在数据库中添加数字。

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

下一步是创建一个带字符串并将其输出到字符串列表中的函数:

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

下一步是获取函数的长度。如果它的长度为2,我们会查看第一个数字,以确定它是在10s还是20s。如果它是" 25",不知何故,做" 20" ++"五"。

正如你所知,我对如何做有点困惑。在过去的两天里,我一直在考虑这个问题,这就是我能想到的。

1 个答案:

答案 0 :(得分:2)

以下是如何模式匹配字符串:

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

但您可能还想考虑更改numWords的签名以获取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
  | ...