home *** CD-ROM | disk | FTP | other *** search
/ PSION CD 2 / PsionCDVol2.iso / Programs / 876 / hugs.sis / CommaInt.lhs < prev    next >
Encoding:
Text File  |  2000-09-21  |  1.6 KB  |  71 lines

  1. This file contains the definition of commaint, a function which takes a
  2. single string argument containing a sequence of digits, and outputs the
  3. same sequence with commas inserted after every group of three digits,
  4. reading from the right hand end of the string.
  5.  
  6. > module CommaInt where
  7. >  commaint = reverse . foldr1 (\x y->x++","++y) . group 3 . reverse
  8. >     where group n = takeWhile (not.null) . map (take n) . iterate (drop n)
  9.  
  10. This definition uses the following library functions:
  11.  
  12.   reverse, (.), foldr1, (++), takeWhile, not, null, map, take, iterate, drop.
  13.  
  14. Example: evaluation of commaint "1234567"
  15.  
  16.            "1234567"
  17.                |
  18.                | reverse
  19.                V
  20.            "7654321" _______________________________
  21.                |                                    \
  22.                | iterate (drop 3)                    |
  23.                V                                     |
  24.            ["7654321", "4321", "1", "", "", ...]     |
  25.                |                                     |
  26.                | map (take 3)                        V  group 3
  27.                V                                     |
  28.            ["765", "432", "1", "", "", ...]          |
  29.                |                                     |
  30.                | takeWhile (not.null)                |
  31.                V     _______________________________/
  32.            ["765", "432", "1"]
  33.                |
  34.                | foldr1 (\x y->x++","++y)
  35.                V
  36.            "765,432,1"
  37.                |
  38.                | reverse
  39.                V
  40.            "1,234,567"
  41.  
  42. In a Hugs session:
  43.  
  44.     ? commaint "1234567"
  45.     1,234,567
  46.     ?
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71.