2021-09-30

Money formatter. List of Char vs String.

Char vs List of Char

Recently seen problem: attempt to put an @ sign after the first letter of a word:

f :: [Char] -> [Char]  -- same as String -> String
f "" = ""
f (x:xs) = x : "@" : xs

This code does not work because "@" is a list containing a single character, which could also be written ['@'], instead of the desired single character '@'. The correct function follows.

f (x:xs) = x : '@' : xs

Practice

  1. money :: Int -> String.

     money 123456789 == "$123,456,789"
     money 1234 == "$1,234"
    

    Advanced: treat the last two digits as cents, so examples look like this:

     moneyCents 123498 == "$1,234.98"
     moneyCents 12350 == "$123.50" -- Advanced only!
    

    Simplified: produce the corresponding list of Int:

     moneySimple 12345678 == [12,345,678]
    

    Very simplified:

     moneySuperSimple [1,2,3,4,5,6,7,8] == [12,345,678]
    
  2. What is the type of the expression:

     q2 = [ ("Ping", 8), ("Pong", 7), ("Table", 19), ("Tennis", 11)]
    
  3. Given (x,y) in a list [(Int, Int)] produce a list of ordered pairs (x,y) for which $y < x^2+30$.

     q3 [(10,125), (8, 104), (5, 9), (20, 500)] == [(10,125), (5,9)]
    
Last modified August 18, 2023: 2022-2023 End State (7352e87)